diff --git a/extras/docker/build_and_push.sh b/extras/docker/build_and_push.sh index 91e6fa15e5..c58a73bf8e 100755 --- a/extras/docker/build_and_push.sh +++ b/extras/docker/build_and_push.sh @@ -1,3 +1,4 @@ #!/bin/bash docker build --rm=true --pull --no-cache --build-arg BRANCH="develop" --build-arg DB_PASS="pandora" -t pandorafms/pandorafms:7 . && \ +[ "$QA_ENV" == "" ] && \ docker push pandorafms/pandorafms:7 diff --git a/pandora_agents/pc/AIX/pandora_agent.conf b/pandora_agents/pc/AIX/pandora_agent.conf index fbea6eb404..f3657d3a7a 100644 --- a/pandora_agents/pc/AIX/pandora_agent.conf +++ b/pandora_agents/pc/AIX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, AIX version +# Version 7.0NG.740, AIX version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/FreeBSD/pandora_agent.conf b/pandora_agents/pc/FreeBSD/pandora_agent.conf index ded3ec4b9c..95fd1090ad 100644 --- a/pandora_agents/pc/FreeBSD/pandora_agent.conf +++ b/pandora_agents/pc/FreeBSD/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, FreeBSD Version +# Version 7.0NG.740, FreeBSD Version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/HP-UX/pandora_agent.conf b/pandora_agents/pc/HP-UX/pandora_agent.conf index 0d3e20d05e..04122feb30 100644 --- a/pandora_agents/pc/HP-UX/pandora_agent.conf +++ b/pandora_agents/pc/HP-UX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, HP-UX Version +# Version 7.0NG.740, HP-UX Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/Linux/pandora_agent.conf b/pandora_agents/pc/Linux/pandora_agent.conf index 5d951d984d..b083e7f3aa 100644 --- a/pandora_agents/pc/Linux/pandora_agent.conf +++ b/pandora_agents/pc/Linux/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, GNU/Linux +# Version 7.0NG.740, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/NT4/pandora_agent.conf b/pandora_agents/pc/NT4/pandora_agent.conf index 1c73d12fc9..4bb88c5b4e 100644 --- a/pandora_agents/pc/NT4/pandora_agent.conf +++ b/pandora_agents/pc/NT4/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, GNU/Linux +# Version 7.0NG.740, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/SunOS/pandora_agent.conf b/pandora_agents/pc/SunOS/pandora_agent.conf index fc59e308e4..a90b7227ca 100644 --- a/pandora_agents/pc/SunOS/pandora_agent.conf +++ b/pandora_agents/pc/SunOS/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, Solaris Version +# Version 7.0NG.740, Solaris Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/pc/Win32/pandora_agent.conf b/pandora_agents/pc/Win32/pandora_agent.conf index f12cb5089c..d750898b70 100644 --- a/pandora_agents/pc/Win32/pandora_agent.conf +++ b/pandora_agents/pc/Win32/pandora_agent.conf @@ -1,6 +1,6 @@ # Base config file for Pandora FMS Windows Agent # (c) 2006-2010 Artica Soluciones Tecnologicas -# Version 7.0NG.738 +# Version 7.0NG.740 # This program is Free Software, you can redistribute it and/or modify it # under the terms of the GNU General Public Licence as published by the Free Software diff --git a/pandora_agents/shellscript/aix/pandora_agent.conf b/pandora_agents/shellscript/aix/pandora_agent.conf index 863ab92907..6a663d6331 100644 --- a/pandora_agents/shellscript/aix/pandora_agent.conf +++ b/pandora_agents/shellscript/aix/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.738, AIX version +# Version 7.0NG.740, AIX version # General Parameters # ================== diff --git a/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf b/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf index f56402fbcc..99e4c62462 100644 --- a/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf +++ b/pandora_agents/shellscript/bsd-ipso/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.738 +# Version 7.0NG.740 # FreeBSD/IPSO version # Licenced under GPL licence, 2003-2007 Sancho Lerena diff --git a/pandora_agents/shellscript/hp-ux/pandora_agent.conf b/pandora_agents/shellscript/hp-ux/pandora_agent.conf index 55576e58fd..7a9d2c4347 100644 --- a/pandora_agents/shellscript/hp-ux/pandora_agent.conf +++ b/pandora_agents/shellscript/hp-ux/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.738, HPUX Version +# Version 7.0NG.740, HPUX Version # General Parameters # ================== diff --git a/pandora_agents/shellscript/linux/pandora_agent.conf b/pandora_agents/shellscript/linux/pandora_agent.conf index a584a597cb..a55d96a952 100644 --- a/pandora_agents/shellscript/linux/pandora_agent.conf +++ b/pandora_agents/shellscript/linux/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738 +# Version 7.0NG.740 # Licensed under GPL license v2, # (c) 2003-2010 Artica Soluciones Tecnologicas # please visit http://pandora.sourceforge.net diff --git a/pandora_agents/shellscript/mac_osx/pandora_agent.conf b/pandora_agents/shellscript/mac_osx/pandora_agent.conf index 18db7a174f..a24a24d16e 100644 --- a/pandora_agents/shellscript/mac_osx/pandora_agent.conf +++ b/pandora_agents/shellscript/mac_osx/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738 +# Version 7.0NG.740 # Licensed under GPL license v2, # (c) 2003-2009 Artica Soluciones Tecnologicas # please visit http://pandora.sourceforge.net diff --git a/pandora_agents/shellscript/openWRT/pandora_agent.conf b/pandora_agents/shellscript/openWRT/pandora_agent.conf index d3266f091d..74d515cb4e 100644 --- a/pandora_agents/shellscript/openWRT/pandora_agent.conf +++ b/pandora_agents/shellscript/openWRT/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738 +# Version 7.0NG.740 # Licensed under GPL license v2, # please visit http://pandora.sourceforge.net diff --git a/pandora_agents/shellscript/solaris/pandora_agent.conf b/pandora_agents/shellscript/solaris/pandora_agent.conf index aa59a262c4..dc915ef18e 100644 --- a/pandora_agents/shellscript/solaris/pandora_agent.conf +++ b/pandora_agents/shellscript/solaris/pandora_agent.conf @@ -1,6 +1,6 @@ # Fichero de configuracion base de agentes de Pandora # Base config file for Pandora agents -# Version 7.0NG.738, Solaris version +# Version 7.0NG.740, Solaris version # General Parameters # ================== diff --git a/pandora_agents/unix/AIX/pandora_agent.conf b/pandora_agents/unix/AIX/pandora_agent.conf index dedf2c366f..de7e97911b 100644 --- a/pandora_agents/unix/AIX/pandora_agent.conf +++ b/pandora_agents/unix/AIX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, AIX version +# Version 7.0NG.740, AIX version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/DEBIAN/control b/pandora_agents/unix/DEBIAN/control index 00e5de0dc5..ce165fde19 100644 --- a/pandora_agents/unix/DEBIAN/control +++ b/pandora_agents/unix/DEBIAN/control @@ -1,5 +1,5 @@ package: pandorafms-agent-unix -Version: 7.0NG.738-190913 +Version: 7.0NG.740-191029 Architecture: all Priority: optional Section: admin diff --git a/pandora_agents/unix/DEBIAN/make_deb_package.sh b/pandora_agents/unix/DEBIAN/make_deb_package.sh index 4035bca720..a4a8dce448 100644 --- a/pandora_agents/unix/DEBIAN/make_deb_package.sh +++ b/pandora_agents/unix/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.738-190913" +pandora_version="7.0NG.740-191029" echo "Test if you has the tools for to make the packages." whereis dpkg-deb | cut -d":" -f2 | grep dpkg-deb > /dev/null diff --git a/pandora_agents/unix/Darwin/pandora_agent.conf b/pandora_agents/unix/Darwin/pandora_agent.conf index 4624a5ceff..34dd1bf4fc 100644 --- a/pandora_agents/unix/Darwin/pandora_agent.conf +++ b/pandora_agents/unix/Darwin/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, GNU/Linux +# Version 7.0NG.740, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2012 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/FreeBSD/pandora_agent.conf b/pandora_agents/unix/FreeBSD/pandora_agent.conf index 0895974d7b..e4ad74ffe7 100644 --- a/pandora_agents/unix/FreeBSD/pandora_agent.conf +++ b/pandora_agents/unix/FreeBSD/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, FreeBSD Version +# Version 7.0NG.740, FreeBSD Version # Licensed under GPL license v2, # Copyright (c) 2003-2016 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/HP-UX/pandora_agent.conf b/pandora_agents/unix/HP-UX/pandora_agent.conf index bfd0612672..e55445fe13 100644 --- a/pandora_agents/unix/HP-UX/pandora_agent.conf +++ b/pandora_agents/unix/HP-UX/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, HP-UX Version +# Version 7.0NG.740, HP-UX Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/Linux/pandora_agent.conf b/pandora_agents/unix/Linux/pandora_agent.conf index e1a83ed6e5..54ace6a811 100644 --- a/pandora_agents/unix/Linux/pandora_agent.conf +++ b/pandora_agents/unix/Linux/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, GNU/Linux +# Version 7.0NG.740, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2014 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/NT4/pandora_agent.conf b/pandora_agents/unix/NT4/pandora_agent.conf index b0841bd0f7..94e32e8056 100644 --- a/pandora_agents/unix/NT4/pandora_agent.conf +++ b/pandora_agents/unix/NT4/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, GNU/Linux +# Version 7.0NG.740, GNU/Linux # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/NetBSD/pandora_agent.conf b/pandora_agents/unix/NetBSD/pandora_agent.conf index 4d96ba223d..71e7d14192 100644 --- a/pandora_agents/unix/NetBSD/pandora_agent.conf +++ b/pandora_agents/unix/NetBSD/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, NetBSD Version +# Version 7.0NG.740, NetBSD Version # Licensed under GPL license v2, # Copyright (c) 2003-2010 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/SunOS/pandora_agent.conf b/pandora_agents/unix/SunOS/pandora_agent.conf index c4a4c578d9..cc89dee501 100644 --- a/pandora_agents/unix/SunOS/pandora_agent.conf +++ b/pandora_agents/unix/SunOS/pandora_agent.conf @@ -1,5 +1,5 @@ # Base config file for Pandora FMS agents -# Version 7.0NG.738, Solaris Version +# Version 7.0NG.740, Solaris Version # Licensed under GPL license v2, # Copyright (c) 2003-2009 Artica Soluciones Tecnologicas # http://www.pandorafms.com diff --git a/pandora_agents/unix/pandora_agent b/pandora_agents/unix/pandora_agent index 35a86a656b..4bbac522b1 100755 --- a/pandora_agents/unix/pandora_agent +++ b/pandora_agents/unix/pandora_agent @@ -41,8 +41,8 @@ my $Sem = undef; # Semaphore used to control the number of threads my $ThreadSem = undef; -use constant AGENT_VERSION => '7.0NG.738'; -use constant AGENT_BUILD => '190913'; +use constant AGENT_VERSION => '7.0NG.740'; +use constant AGENT_BUILD => '191029'; # Agent log default file size maximum and instances use constant DEFAULT_MAX_LOG_SIZE => 600000; @@ -239,6 +239,15 @@ my $tentacle_pid = undef; # PID of udp_server my $udp_server_pid = undef; +# BrokerFlag +my $BrokerFlag = 0; + +# Global loop counter. +my $LoopCounter = 0; + +# Define a max value for loopCounter to avoid overflow. +use constant MAX_LOOP_COUNTER => 1000000000; + ################################################################################ # Print usage information and exit. ################################################################################ @@ -1385,6 +1394,7 @@ sub sleep_agent { exit (0); } + $LoopCounter = ($LoopCounter + 1) % MAX_LOOP_COUNTER; return $iter_base_time; } @@ -1699,6 +1709,14 @@ sub exec_module { } # Check module interval + if ($BrokerFlag > 0) { + if ($LoopCounter == 0) { + $module->{'counter'} = $module->{'intensive_interval'}; + } else { + $module->{'counter'} = (($LoopCounter -1 ) % $module->{'intensive_interval'}); + } + } + if (++($module->{'counter'}) < $module->{'intensive_interval'}) { $ThreadSem->up () if (defined ($ThreadSem) && $Conf{'agent_threads'} > 1); return; @@ -2985,7 +3003,6 @@ while (1) { @BrokerPid = (); my @broker_agents = read_config ('broker_agent'); foreach my $broker_agent (@broker_agents) { - # Create broker conf file if it does not exist if (! -e "$ConfDir/${broker_agent}.conf") { write_broker_conf($broker_agent); @@ -2995,7 +3012,9 @@ while (1) { # Broker agent if ($main_agent == 0) { - + # Mark broker flag. + $BrokerFlag = 1; + # Set the configuration file $ConfFile = "${broker_agent}.conf"; diff --git a/pandora_agents/unix/pandora_agent.redhat.spec b/pandora_agents/unix/pandora_agent.redhat.spec index 965a1aa0d1..79f2310c11 100644 --- a/pandora_agents/unix/pandora_agent.redhat.spec +++ b/pandora_agents/unix/pandora_agent.redhat.spec @@ -2,8 +2,8 @@ #Pandora FMS Linux Agent # %define name pandorafms_agent_unix -%define version 7.0NG.738 -%define release 190913 +%define version 7.0NG.740 +%define release 191029 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent.spec b/pandora_agents/unix/pandora_agent.spec index 55bda1c48a..392fa174ce 100644 --- a/pandora_agents/unix/pandora_agent.spec +++ b/pandora_agents/unix/pandora_agent.spec @@ -2,8 +2,8 @@ #Pandora FMS Linux Agent # %define name pandorafms_agent_unix -%define version 7.0NG.738 -%define release 190913 +%define version 7.0NG.740 +%define release 191029 Summary: Pandora FMS Linux agent, PERL version Name: %{name} diff --git a/pandora_agents/unix/pandora_agent_installer b/pandora_agents/unix/pandora_agent_installer index f9eaab41c0..cc4b78b51c 100755 --- a/pandora_agents/unix/pandora_agent_installer +++ b/pandora_agents/unix/pandora_agent_installer @@ -9,8 +9,8 @@ # Please see http://www.pandorafms.org. This code is licensed under GPL 2.0 license. # ********************************************************************** -PI_VERSION="7.0NG.738" -PI_BUILD="190913" +PI_VERSION="7.0NG.740" +PI_BUILD="191029" OS_NAME=`uname -s` FORCE=0 @@ -162,7 +162,15 @@ uninstall () { rm -Rf $PANDORA_BASE$PANDORA_EXEC_BIN 2> /dev/null rm -Rf $PANDORA_BASE$PANDORA_REVENT_BIN 2> /dev/null rm -f $DESTDIR/etc/logrotate.d/pandora_agent - + + # Remove systemd service if exists + if [ $(systemctl --v | grep systemd | wc -l) != 0 ] + then + PANDORA_AGENT_SERVICE="/etc/systemd/system/pandora_agent_daemon.service" + rm -f $PANDORA_AGENT_SERVICE + systemctl reset-failed + fi + #Test if exist Pandora Server in this machine if [ -d $PANDORA_BASE$PANDORA_TEMP/data_in ] then @@ -465,6 +473,22 @@ install () { else RCDIRS="/etc/rc2.d /etc/rc3.d" fi + + # Create systemd service + if [ $(systemctl --v | grep systemd | wc -l) != 0 ] + then + echo "Creating systemd service for pandora_agent_daemon" + + PANDORA_AGENT_SERVICE="/etc/systemd/system/pandora_agent_daemon.service" + EXEC_START='ExecStart='$PANDORA_BASE$PANDORA_BIN' '$PANDORA_BASE$PANDORA_CFG + + rm -f $PANDORA_AGENT_SERVICE + cp pandora_agent_daemon.service $PANDORA_AGENT_SERVICE + + sed -i "s|^ExecStart=.*$|$EXEC_START|g" $PANDORA_AGENT_SERVICE + + systemctl daemon-reload + fi fi [ "$RCDIRS" ] && for RCDIR in $RCDIRS do diff --git a/pandora_agents/win32/bin/pandora_agent.conf b/pandora_agents/win32/bin/pandora_agent.conf index c74dadfff6..79660e5b5d 100644 --- a/pandora_agents/win32/bin/pandora_agent.conf +++ b/pandora_agents/win32/bin/pandora_agent.conf @@ -1,6 +1,6 @@ # Base config file for Pandora FMS Windows Agent # (c) 2006-2017 Artica Soluciones Tecnologicas -# Version 7.0NG.738 +# Version 7.0NG.740 # This program is Free Software, you can redistribute it and/or modify it # under the terms of the GNU General Public Licence as published by the Free Software diff --git a/pandora_agents/win32/installer/pandora.mpi b/pandora_agents/win32/installer/pandora.mpi index 5b62310d00..730edbe5de 100644 --- a/pandora_agents/win32/installer/pandora.mpi +++ b/pandora_agents/win32/installer/pandora.mpi @@ -3,7 +3,7 @@ AllowLanguageSelection {Yes} AppName -{Pandora FMS Windows Agent v7.0NG.738} +{Pandora FMS Windows Agent v7.0NG.740} ApplicationID {17E3D2CF-CA02-406B-8A80-9D31C17BD08F} @@ -186,7 +186,7 @@ UpgradeApplicationID {} Version -{190913} +{191029} ViewReadme {Yes} diff --git a/pandora_agents/win32/modules/pandora_module.cc b/pandora_agents/win32/modules/pandora_module.cc index e7c751d367..7cbde21ca7 100644 --- a/pandora_agents/win32/modules/pandora_module.cc +++ b/pandora_agents/win32/modules/pandora_module.cc @@ -1422,48 +1422,48 @@ Pandora_Module::evaluatePreconditions () { buffer[read] = '\0'; output += (char *) buffer; } - - try { - double_output = Pandora_Strutils::strtodouble (output); - } catch (Pandora_Strutils::Invalid_Conversion e) { - double_output = 0; + + try { + double_output = Pandora_Strutils::strtodouble (output); + } catch (Pandora_Strutils::Invalid_Conversion e) { + double_output = 0; + } + + if (dwRet == WAIT_OBJECT_0) { + break; + } else if(this->getTimeout() < GetTickCount() - tickbase) { + /* STILL_ACTIVE */ + TerminateProcess(pi.hThread, STILL_ACTIVE); + pandoraLog ("evaluatePreconditions: %s timed out (retcode: %d)", this->module_name.c_str (), STILL_ACTIVE); + break; + } } - if (dwRet == WAIT_OBJECT_0) { - break; - } else if(this->getTimeout() < GetTickCount() - tickbase) { - /* STILL_ACTIVE */ - TerminateProcess(pi.hThread, STILL_ACTIVE); - pandoraLog ("evaluatePreconditions: %s timed out (retcode: %d)", this->module_name.c_str (), STILL_ACTIVE); - break; + GetExitCodeProcess (pi.hProcess, &retval); + + if (retval != 0) { + if (! TerminateJobObject (job, 0)) { + pandoraLog ("evaluatePreconditions: TerminateJobObject failed. (error %d)", + GetLastError ()); + } + if (retval != STILL_ACTIVE) { + pandoraLog ("evaluatePreconditions: %s did not executed well (retcode: %d)", + this->module_name.c_str (), retval); + } + /* Close job, process and thread handles. */ + CloseHandle (job); + CloseHandle (pi.hProcess); + CloseHandle (pi.hThread); + CloseHandle (new_stdout); + CloseHandle (out_read); + return 0; } - } - - GetExitCodeProcess (pi.hProcess, &retval); - - if (retval != 0) { - if (! TerminateJobObject (job, 0)) { - pandoraLog ("evaluatePreconditions: TerminateJobObject failed. (error %d)", - GetLastError ()); - } - if (retval != STILL_ACTIVE) { - pandoraLog ("evaluatePreconditions: %s did not executed well (retcode: %d)", - this->module_name.c_str (), retval); - } + /* Close job, process and thread handles. */ CloseHandle (job); CloseHandle (pi.hProcess); CloseHandle (pi.hThread); - CloseHandle (new_stdout); - CloseHandle (out_read); - return 0; } - - /* Close job, process and thread handles. */ - CloseHandle (job); - CloseHandle (pi.hProcess); - CloseHandle (pi.hThread); - } CloseHandle (new_stdout); CloseHandle (out_read); @@ -1693,4 +1693,18 @@ Pandora_Module::getAsync () { return this->async; } +/** + * Get current exections + */ +long +Pandora_Module::getExecutions () { + return this->executions; +} +/** + * Set current execution (global) used for brokers. + */ +void +Pandora_Module::setExecutions (long executions) { + this->executions = executions; +} diff --git a/pandora_agents/win32/modules/pandora_module.h b/pandora_agents/win32/modules/pandora_module.h index c766766950..3b9d6c15a4 100644 --- a/pandora_agents/win32/modules/pandora_module.h +++ b/pandora_agents/win32/modules/pandora_module.h @@ -234,6 +234,8 @@ namespace Pandora_Modules { int getTimeout (); string getSave (); bool getAsync (); + void setExecutions(long executions=0); + long getExecutions(); virtual string getXml (); diff --git a/pandora_agents/win32/pandora.cc b/pandora_agents/win32/pandora.cc index 22d0d1eff5..823b486b0e 100644 --- a/pandora_agents/win32/pandora.cc +++ b/pandora_agents/win32/pandora.cc @@ -30,7 +30,7 @@ using namespace Pandora; using namespace Pandora_Strutils; #define PATH_SIZE _MAX_PATH+1 -#define PANDORA_VERSION ("7.0NG.738(Build 190913)") +#define PANDORA_VERSION ("7.0NG.740(Build 191029)") string pandora_path; string pandora_dir; diff --git a/pandora_agents/win32/pandora_windows_service.cc b/pandora_agents/win32/pandora_windows_service.cc index 275ee60724..b62fc1f70d 100644 --- a/pandora_agents/win32/pandora_windows_service.cc +++ b/pandora_agents/win32/pandora_windows_service.cc @@ -1849,7 +1849,7 @@ Pandora_Windows_Service::sendBufferedXml (string path) { } void -Pandora_Windows_Service::pandora_run_broker (string config) { +Pandora_Windows_Service::pandora_run_broker (string config, long executions) { Pandora_Agent_Conf *conf = NULL; string server_addr; unsigned char data_flag = 0; @@ -1876,7 +1876,10 @@ Pandora_Windows_Service::pandora_run_broker (string config) { Pandora_Module *module; module = this->broker_modules->getCurrentValue (); - + + /* Keep executions matching main agent */ + module->setExecutions(executions); + /* Check preconditions */ if (module->evaluatePreconditions () == 0) { pandoraDebug ("Preconditions not matched for module %s", module->getName ().c_str ()); @@ -2074,7 +2077,7 @@ Pandora_Windows_Service::pandora_run (int forced_run) { check_broker_agents(all_conf); for (i=0;i'; echo ''; break; - - case 'TTRT': - break; - - case 'TTO': - break; - - case 'MTBF': - break; - - case 'MTTR': - break; } echo "\n"; diff --git a/pandora_console/extensions/resource_registration.php b/pandora_console/extensions/resource_registration.php index c43e2a97f2..dae61e3a78 100755 --- a/pandora_console/extensions/resource_registration.php +++ b/pandora_console/extensions/resource_registration.php @@ -375,18 +375,6 @@ function process_upload_xml_report($xml, $group_filter=0) $values['line_separator'] = io_safe_input($item['line_separator']); $values['column_separator'] = io_safe_input($item['column_separator']); break; - - case 'TTRT': - break; - - case 'TTO': - break; - - case 'MTBF': - break; - - case 'MTTR': - break; } if (empty($agents_item)) { diff --git a/pandora_console/extensions/sample_agent.php b/pandora_console/extensions/sample_agent.php new file mode 100644 index 0000000000..ba92debae9 --- /dev/null +++ b/pandora_console/extensions/sample_agent.php @@ -0,0 +1,66 @@ + $id_agente], 'id_agente_modulo'); + $count_modules = count($modules); + + // Update of layout 1 (Rack sample). + $images_rack_server = [ + 'rack_server_rack', + 'rack_server', + 'rack_switch', + 'rack_firewall', + 'rack_double_server', + 'rack_frame', + 'rack_pdu', + ]; + $query = 'UPDATE `tlayout_data` SET `id_agent` = '.$id_agente.', `id_agente_modulo` = CASE '; + for ($i = 0; $i < $count_modules; $i++) { + $query .= 'WHEN `image` = "'.$images_rack_server[$i].'" THEN '.$modules[$i]['id_agente_modulo'].' '; + } + + $query .= 'END WHERE `id_layout` = 1 AND `image` IN ("'.implode('","', $images_rack_server).'");'; + + db_process_sql($query); + // Update of layout 2 (Dashboard). + $query = 'UPDATE `tlayout_data` SET `id_agent`= '.$id_agente.', `id_agente_modulo` = CASE '; + $query .= 'WHEN `id` = 107 THEN '.$modules[0]['id_agente_modulo'].' '; + $query .= 'WHEN `id` = 108 THEN '.$modules[1]['id_agente_modulo'].' '; + $query .= 'WHEN `id` = 109 THEN '.$modules[2]['id_agente_modulo'].' '; + $query .= 'WHEN `id` = 110 THEN '.$modules[2]['id_agente_modulo'].' '; + $query .= 'WHEN `id` = 111 THEN '.$modules[3]['id_agente_modulo'].' '; + $query .= 'WHEN `id` = 112 THEN '.$modules[4]['id_agente_modulo'].' '; + $query .= 'WHEN `id` = 113 THEN '.$modules[5]['id_agente_modulo'].' '; + $query .= 'WHEN `id` = 114 THEN '.$modules[6]['id_agente_modulo'].' '; + $query .= 'END WHERE `id_layout` = 2 AND `id` IN (107,108,109,110,111,112,113,114);'; + + db_process_sql($query); + + // This setting will avoid regenerate all the times the visual consoles. + config_update_value('sample_agent_deployed', 1); +} + +extensions_add_main_function('sample_agent_deployment'); diff --git a/pandora_console/extras/mr/32.sql b/pandora_console/extras/mr/32.sql index 3100d73092..2e50885f21 100644 --- a/pandora_console/extras/mr/32.sql +++ b/pandora_console/extras/mr/32.sql @@ -1,7 +1,44 @@ START TRANSACTION; +ALTER TABLE `tdatabase` MODIFY `last_error` text; +ALTER TABLE `tdatabase` MODIFY `host` VARCHAR(255) DEFAULT ''; +ALTER TABLE `tdatabase` ADD COLUMN `label` VARCHAR(255) DEFAULT ''; +ALTER TABLE `tdatabase` MODIFY `os_user` VARCHAR(255) DEFAULT ''; +ALTER TABLE `tdatabase` MODIFY `db_port` INT UNSIGNED NOT NULL DEFAULT 3306; +ALTER TABLE `tdatabase` MODIFY `os_port` INT UNSIGNED NOT NULL DEFAULT 22; +ALTER TABLE `tdatabase` ADD COLUMN `ssh_key` TEXT; +ALTER TABLE `tdatabase` ADD COLUMN `ssh_pubkey` TEXT; + +UPDATE `tdatabase` set `label`=`host`; + UPDATE `tlayout_data` SET `height` = 70 , `width` = 70 WHERE `height` = 0 && `width` = 0 && image NOT LIKE '%dot%' && ((`type` IN (0,5)) || (`type` = 10 && `image` IS NOT NULL && `image` != '' && `image` != 'none') || (`type` = 11 && `image` IS NOT NULL && `image` != '' && `image` != 'none' && `show_statistics` = 0)); -COMMIT; \ No newline at end of file +INSERT INTO `tconfig` (`token`, `value`) VALUES ('integria_enabled', 0); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('integria_user', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('integria_pass', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('integria_hostname', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('integria_api_pass', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('integria_req_timeout', 5); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('default_group', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('default_criticity', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('default_creator', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('default_owner', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('incident_type', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('incident_status', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('incident_title', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('incident_content', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_default_group', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_default_criticity', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_default_creator', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_default_owner', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_type', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_status', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_title', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_content', ''); + +ALTER TABLE `treport_content` ADD COLUMN `uncompressed_module` TINYINT DEFAULT '0'; +ALTER TABLE `treport_content_template` ADD COLUMN `uncompressed_module` TINYINT DEFAULT '0'; + +COMMIT; diff --git a/pandora_console/extras/mr/33.sql b/pandora_console/extras/mr/33.sql new file mode 100644 index 0000000000..31af5570e4 --- /dev/null +++ b/pandora_console/extras/mr/33.sql @@ -0,0 +1,5 @@ +START TRANSACTION; + +ALTER TABLE `tlayout_template_data` ADD COLUMN `cache_expiration` INTEGER UNSIGNED NOT NULL DEFAULT 0; + +COMMIT; diff --git a/pandora_console/extras/pandora_diag.php b/pandora_console/extras/pandora_diag.php index 9258a3be42..eb9a199456 100644 --- a/pandora_console/extras/pandora_diag.php +++ b/pandora_console/extras/pandora_diag.php @@ -726,7 +726,7 @@ render_info_data( echo "".__(' Pandora FMS Licence Information').''; render_row(html_print_textarea('keys[customer_key]', 10, 255, $settings->customer_key, 'style="height:40px; width:450px;"', true), 'Customer key'); - render_row($license['expiry_date'], 'Expires'); + render_row($license['expiry_date'], $license['expiry_caption']); render_row($license['limit'].' agents', 'Platform Limit'); render_row($license['count'].' agents', 'Current Platform Count'); render_row($license['count_enabled'].' agents', 'Current Platform Count (enabled: items)'); diff --git a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql index 704ab61d74..d7e416c951 100644 --- a/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql +++ b/pandora_console/extras/pandoradb_migrate_6.0_to_7.0.mysql.sql @@ -219,14 +219,17 @@ CREATE TABLE IF NOT EXISTS `tdashboard` ( -- Table `tdatabase` -- --------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS `tdatabase` ( - `id` int(10) unsigned NOT NULL auto_increment, - `host` varchar(100) default '', - `os_port` int(4) unsigned default '22', - `os_user` varchar(100) default '', - `db_port` int(4) unsigned default '3306', + `id` INT(10) unsigned NOT NULL auto_increment, + `host` VARCHAR(255) default '', + `label` VARCHAR(255) default '', + `os_port` INT UNSIGNED NOT NULL DEFAULT 22, + `os_user` VARCHAR(255) default '', + `db_port` INT UNSIGNED NOT NULL DEFAULT 3306, `status` tinyint(1) unsigned default '0', `action` tinyint(1) unsigned default '0', - `last_error` varchar(255) default '', + `ssh_key` TEXT, + `ssh_pubkey` TEXT, + `last_error` TEXT, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET=utf8 ; @@ -798,6 +801,7 @@ ALTER TABLE `treport_content_template` ADD COLUMN `agent_min_value` TINYINT(1) D ALTER TABLE `treport_content_template` ADD COLUMN `current_month` TINYINT(1) DEFAULT '1'; ALTER TABLE `treport_content_template` ADD COLUMN `failover_mode` tinyint(1) DEFAULT '1'; ALTER TABLE `treport_content_template` ADD COLUMN `failover_type` tinyint(1) DEFAULT '1'; +ALTER TABLE `treport_content_template` ADD COLUMN `uncompressed_module` TINYINT DEFAULT '0'; -- ----------------------------------------------------- -- Table `treport_content_sla_com_temp` (treport_content_sla_combined_template) @@ -1243,19 +1247,39 @@ ALTER TABLE titem MODIFY `source_data` int(10) unsigned; INSERT INTO `tconfig` (`token`, `value`) VALUES ('big_operation_step_datos_purge', '100'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('small_operation_step_datos_purge', '1000'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('days_autodisable_deletion', '30'); -INSERT INTO `tconfig` (`token`, `value`) VALUES ('MR', 31); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('MR', 32); INSERT INTO `tconfig` (`token`, `value`) VALUES ('custom_docs_logo', 'default_docs.png'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('custom_support_logo', 'default_support.png'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('custom_logo_white_bg_preview', 'pandora_logo_head_white_bg.png'); UPDATE tconfig SET value = 'https://licensing.artica.es/pandoraupdate7/server.php' WHERE token='url_update_manager'; DELETE FROM `tconfig` WHERE `token` = 'current_package_enterprise'; -INSERT INTO `tconfig` (`token`, `value`) VALUES ('current_package_enterprise', '737'); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('current_package_enterprise', '739'); INSERT INTO `tconfig` (`token`, `value`) VALUES ('status_monitor_fields', 'policy,agent,data_type,module_name,server_type,interval,status,graph,warn,data,timestamp'); UPDATE `tconfig` SET `value` = 'mini_severity,evento,id_agente,estado,timestamp' WHERE `token` LIKE 'event_fields'; -DELETE FROM `tconfig` WHERE `token` LIKE 'integria_enabled'; DELETE FROM `tconfig` WHERE `token` LIKE 'integria_api_password'; DELETE FROM `tconfig` WHERE `token` LIKE 'integria_inventory'; DELETE FROM `tconfig` WHERE `token` LIKE 'integria_url'; +INSERT INTO `tconfig` (`token`, `value`) VALUES ('integria_user', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('integria_pass', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('integria_hostname', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('integria_api_pass', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('integria_req_timeout', 5); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('default_group', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('default_criticity', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('default_creator', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('default_owner', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('incident_type', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('incident_status', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('incident_title', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('incident_content', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_default_group', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_default_criticity', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_default_creator', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_default_owner', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_type', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_status', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_title', ''); +INSERT INTO `tconfig` (`token`, `value`) VALUES ('cr_incident_content', ''); -- --------------------------------------------------------------------- -- Table `tconfig_os` @@ -1454,6 +1478,7 @@ ALTER TABLE `treport_content` ADD COLUMN `current_month` TINYINT(1) DEFAULT '1'; ALTER TABLE `treport_content` ADD COLUMN `failover_mode` tinyint(1) DEFAULT '0'; ALTER TABLE `treport_content` ADD COLUMN `failover_type` tinyint(1) DEFAULT '0'; ALTER table `treport_content` MODIFY COLUMN `name` varchar(300) NULL; +ALTER TABLE `treport_content` ADD COLUMN `uncompressed_module` TINYINT DEFAULT '0'; -- --------------------------------------------------------------------- -- Table `tmodule_relationship` @@ -1882,6 +1907,7 @@ CREATE TABLE IF NOT EXISTS `tlayout_template_data` ( `linked_layout_status_as_service_warning` FLOAT(20, 3) NOT NULL default 0, `linked_layout_status_as_service_critical` FLOAT(20, 3) NOT NULL default 0, `linked_layout_node_id` INT(10) NOT NULL default 0, + `cache_expiration` INTEGER UNSIGNED NOT NULL default 0, PRIMARY KEY(`id`), FOREIGN KEY (`id_layout_template`) REFERENCES tlayout_template(`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB DEFAULT CHARSET=utf8; diff --git a/pandora_console/general/firts_task/HA_cluster_builder.php b/pandora_console/general/firts_task/HA_cluster_builder.php index fa85e28381..6d82d94ad0 100644 --- a/pandora_console/general/firts_task/HA_cluster_builder.php +++ b/pandora_console/general/firts_task/HA_cluster_builder.php @@ -1,15 +1,25 @@ - true, 'message' => __('There are no HA clusters defined yet.') ]); ?> @@ -44,8 +52,9 @@ ui_print_info_message(['no_close' => true, 'message' => __('There are no HA clus

"; + echo "
"; ?> true, 'message' => __('There are no HA clus ?> - diff --git a/pandora_console/general/firts_task/planned_downtime.php b/pandora_console/general/firts_task/planned_downtime.php index dcd98fdebb..21bfb4b083 100644 --- a/pandora_console/general/firts_task/planned_downtime.php +++ b/pandora_console/general/firts_task/planned_downtime.php @@ -33,7 +33,7 @@ ui_require_css_file('firts_task'); ); ?>

-
+
diff --git a/pandora_console/godmode/agentes/agent_manager.php b/pandora_console/godmode/agentes/agent_manager.php index 6ee2343fc0..d6b9448576 100644 --- a/pandora_console/godmode/agentes/agent_manager.php +++ b/pandora_console/godmode/agentes/agent_manager.php @@ -765,7 +765,7 @@ $table_adv_agent_icon .= html_print_select( ).''; if ($config['activate_gis']) { - $table_adv_gis = '

'.__('Ignore new GIS data:').'

'; + $table_adv_gis = '

'.__('Update new GIS data:').'

'; if ($new_agent) { $update_gis_data = true; } diff --git a/pandora_console/godmode/agentes/agent_wizard.wmi_explorer.php b/pandora_console/godmode/agentes/agent_wizard.wmi_explorer.php index b40cf80855..47a5cc5a35 100644 --- a/pandora_console/godmode/agentes/agent_wizard.wmi_explorer.php +++ b/pandora_console/godmode/agentes/agent_wizard.wmi_explorer.php @@ -353,7 +353,7 @@ html_print_table($table); echo "
"; echo ''; html_print_submit_button(__('WMI Explore'), 'wmi_explore', false, ['class' => 'sub next']); -echo '
'; +echo '

'; if ($wmiexplore && $fail) { ui_print_error_message(__('Unable to do WMI explorer')); @@ -364,7 +364,7 @@ unset($table); echo ''; if ($wmiexplore && !$fail) { - echo ''; + echo '
'; echo "
"; echo ''; @@ -379,7 +379,7 @@ if ($wmiexplore && !$fail) { // Namespace html_print_input_hidden('server_to_exec', $server_to_exec); - $table->width = '98%'; + $table->width = '100%'; // Mode selector $modes = []; @@ -404,7 +404,7 @@ if ($wmiexplore && !$fail) { $table->colspan[1][0] = 2; $table->data[1][2] = ''.__('Modules').''; - $table->cellstyle[1][2] = 'vertical-align: middle;'; + $table->cellstyle[1][2] = 'text-align: center;'; // Components list $table->data[2][0] = '
'; @@ -495,7 +495,7 @@ if ($wmiexplore && !$fail) { 'width: 300px;' ); $table->data[2][0] .= '
'; - $table->cellstyle[2][0] = 'vertical-align: top; text-align: center;'; + $table->cellstyle[2][0] = 'vertical-align: bottom; text-align: center;'; // Components arrow diff --git a/pandora_console/godmode/agentes/configurar_agente.php b/pandora_console/godmode/agentes/configurar_agente.php index e97fa7cf39..55116f940a 100644 --- a/pandora_console/godmode/agentes/configurar_agente.php +++ b/pandora_console/godmode/agentes/configurar_agente.php @@ -1382,8 +1382,8 @@ if ($update_module || $create_module) { $ff_event_normal = (int) get_parameter('ff_event_normal'); $ff_event_warning = (int) get_parameter('ff_event_warning'); $ff_event_critical = (int) get_parameter('ff_event_critical'); - $ff_type = (int) get_parameter('ff_type'); - $each_ff = (int) get_parameter('each_ff'); + $ff_type = (int) get_parameter('ff_type', $module['ff_type']); + $each_ff = (int) get_parameter('each_ff', $module['each_ff']); $ff_timeout = (int) get_parameter('ff_timeout'); $unit = (string) get_parameter('unit'); $id_tag = (array) get_parameter('id_tag_selected'); diff --git a/pandora_console/godmode/agentes/module_manager.php b/pandora_console/godmode/agentes/module_manager.php index 6ad5267c0e..b7b1d296ec 100644 --- a/pandora_console/godmode/agentes/module_manager.php +++ b/pandora_console/godmode/agentes/module_manager.php @@ -842,7 +842,9 @@ foreach ($modules as $module) { $module['str_warning'], $module['max_critical'], $module['min_critical'], - $module['str_critical'] + $module['str_critical'], + $module['warning_inverse'], + $module['critical_inverse'] ); } else { $data[7] = ''; diff --git a/pandora_console/godmode/agentes/module_manager_editor_common.php b/pandora_console/godmode/agentes/module_manager_editor_common.php index ac110b0d6f..5a4653fc29 100644 --- a/pandora_console/godmode/agentes/module_manager_editor_common.php +++ b/pandora_console/godmode/agentes/module_manager_editor_common.php @@ -1191,49 +1191,54 @@ $table_relations->data[-1][3] .= html_print_image('images/lock.png', true).' $table_relations->data[-1][4] = ''; $table_relations->data[-1][4] .= html_print_image('images/cross.png', true).''; -$module_relations = modules_get_relations(['id_module' => $id_agent_module]); -if (!$module_relations) { - $module_relations = []; -} $relations_count = 0; -foreach ($module_relations as $key => $module_relation) { - if ($module_relation['module_a'] == $id_agent_module) { - $module_id = $module_relation['module_b']; - $agent_id = modules_give_agent_id_from_module_id( - $module_relation['module_b'] - ); - } else { - $module_id = $module_relation['module_a']; - $agent_id = modules_give_agent_id_from_module_id( - $module_relation['module_a'] - ); +if ($id_agent_module) { + $module_relations = modules_get_relations(['id_module' => $id_agent_module]); + + if (!$module_relations) { + $module_relations = []; } - $agent_name = ui_print_agent_name($agent_id, true); + $relations_count = 0; + foreach ($module_relations as $key => $module_relation) { + if ($module_relation['module_a'] == $id_agent_module) { + $module_id = $module_relation['module_b']; + $agent_id = modules_give_agent_id_from_module_id( + $module_relation['module_b'] + ); + } else { + $module_id = $module_relation['module_a']; + $agent_id = modules_give_agent_id_from_module_id( + $module_relation['module_a'] + ); + } - $module_name = modules_get_agentmodule_name($module_id); - if (empty($module_name) || $module_name == 'false') { - $module_name = $module_id; + $agent_name = ui_print_agent_name($agent_id, true); + + $module_name = modules_get_agentmodule_name($module_id); + if (empty($module_name) || $module_name == 'false') { + $module_name = $module_id; + } + + if ($module_relation['disable_update']) { + $disabled_update_class = ''; + } else { + $disabled_update_class = 'alpha50'; + } + + // Agent name. + $table_relations->data[$relations_count][0] = $agent_name; + // Module name. + $table_relations->data[$relations_count][1] = "".ui_print_truncate_text($module_name, 'module_medium', true, true, true, '[…]').''; + // Type. + $table_relations->data[$relations_count][2] = ($module_relation['type'] === 'direct') ? __('Direct') : __('Failover'); + // Lock relationship updates. + $table_relations->data[$relations_count][3] = ''.html_print_image('images/lock.png', true).''; + // Delete relationship. + $table_relations->data[$relations_count][4] = ''.html_print_image('images/cross.png', true).''; + $relations_count++; } - - if ($module_relation['disable_update']) { - $disabled_update_class = ''; - } else { - $disabled_update_class = 'alpha50'; - } - - // Agent name. - $table_relations->data[$relations_count][0] = $agent_name; - // Module name. - $table_relations->data[$relations_count][1] = "".ui_print_truncate_text($module_name, 'module_medium', true, true, true, '[…]').''; - // Type. - $table_relations->data[$relations_count][2] = ($module_relation['type'] === 'direct') ? __('Direct') : __('Failover'); - // Lock relationship updates. - $table_relations->data[$relations_count][3] = ''.html_print_image('images/lock.png', true).''; - // Delete relationship. - $table_relations->data[$relations_count][4] = ''.html_print_image('images/cross.png', true).''; - $relations_count++; } html_print_input_hidden('module_relations_count', $relations_count); diff --git a/pandora_console/godmode/agentes/planned_downtime.editor.php b/pandora_console/godmode/agentes/planned_downtime.editor.php index eef8d5fbdf..ebf64a87c1 100644 --- a/pandora_console/godmode/agentes/planned_downtime.editor.php +++ b/pandora_console/godmode/agentes/planned_downtime.editor.php @@ -827,7 +827,7 @@ $table->data[5][1] = "
'; -echo ''; +echo ''; if ($id_downtime > 0) { echo ''; @@ -929,7 +929,7 @@ if ($id_downtime > 0) { $disabled_add_button = true; } - echo ""; + echo ""; html_print_select_groups(false, $access, true, 'filter_group', $filter_group, '', '', '', false, false, true, '', false, 'min-width:180px;margin-right:15px;'); html_print_checkbox('recursion', 1, $recursion, false, false, ''); @@ -939,7 +939,7 @@ if ($id_downtime > 0) { echo ''; // Show available agents to include into downtime echo '

'.__('Available agents').':

'; - echo ""; + echo ""; echo html_print_select($agents, 'id_agents[]', -1, '', _('Any'), -2, false, true, true, '', false, 'width: 180px;'); @@ -1085,7 +1085,7 @@ if ($id_downtime > 0) { $data[5] = ''.html_print_image('images/config.png', true, ['border' => '0', 'alt' => __('Delete')]).''; } - $data[5] .= ''.html_print_image('images/cross.png', true, ['border' => '0', 'alt' => __('Delete')]).''; + $data[5] .= ''.html_print_image('images/cross.png', true, ['border' => '0', 'alt' => __('Delete')]).''; } $table->data['agent_'.$downtime_agent['id_agente']] = $data; diff --git a/pandora_console/godmode/agentes/planned_downtime.list.php b/pandora_console/godmode/agentes/planned_downtime.list.php index 49a72f125d..01f30afba6 100755 --- a/pandora_console/godmode/agentes/planned_downtime.list.php +++ b/pandora_console/godmode/agentes/planned_downtime.list.php @@ -357,7 +357,7 @@ if (!$downtimes && !$filter_performed) { // No downtimes cause the user performed a search. else if (!$downtimes) { // Filter form. - echo ""; + echo ""; html_print_table($table_form); echo ''; @@ -369,7 +369,7 @@ else if (!$downtimes) { // Create button. if ($write_permisson) { echo ' '; - echo ''; + echo ''; html_print_submit_button(__('Create'), 'create', false, 'class="sub next"'); echo ''; } @@ -378,11 +378,11 @@ else if (!$downtimes) { } // Has downtimes. else { - echo ""; + echo ""; html_print_table($table_form); echo ''; - ui_pagination($downtimes_number, "index.php?sec=estado&sec2=godmode/agentes/planned_downtime.list&$filter_params_str", $offset); + ui_pagination($downtimes_number, "index.php?sec=extensions&sec2=godmode/agentes/planned_downtime.list&$filter_params_str", $offset); // User groups with AR, AD or AW permission. $groupsAD = users_get_groups($config['id_user'], $access); @@ -476,7 +476,7 @@ else { if (in_array($downtime['id_group'], $groupsAD)) { // Stop button if ($downtime['type_execution'] == 'once' && $downtime['executed'] == 1) { - $data['stop'] = ''.html_print_image('images/cancel.png', true, ['title' => __('Stop downtime')]); + $data['stop'] = ''.html_print_image('images/cancel.png', true, ['title' => __('Stop downtime')]); } else { $data['stop'] = ''; } @@ -484,12 +484,12 @@ else { // Edit & delete buttons. if ($downtime['executed'] == 0) { // Edit. - $data['edit'] = ''.html_print_image('images/config.png', true, ['title' => __('Update')]).''; + $data['edit'] = ''.html_print_image('images/config.png', true, ['title' => __('Update')]).''; // Delete. - $data['delete'] = ''.html_print_image('images/cross.png', true, ['title' => __('Delete')]); + $data['delete'] = ''.html_print_image('images/cross.png', true, ['title' => __('Delete')]); } else if ($downtime['executed'] == 1 && $downtime['type_execution'] == 'once') { // Edit. - $data['edit'] = ''.html_print_image('images/config.png', true, ['title' => __('Update')]).''; + $data['edit'] = ''.html_print_image('images/config.png', true, ['title' => __('Update')]).''; // Delete. $data['delete'] = __('N/A'); } else { @@ -515,7 +515,7 @@ else { } html_print_table($table); - ui_pagination($downtimes_number, "index.php?sec=estado&sec2=godmode/agentes/planned_downtime.list&$filter_params_str", $offset, 0, false, 'offset', true, 'pagination-bottom'); + ui_pagination($downtimes_number, "index.php?sec=extensions&sec2=godmode/agentes/planned_downtime.list&$filter_params_str", $offset, 0, false, 'offset', true, 'pagination-bottom'); echo '
'; // CSV export button. @@ -532,7 +532,7 @@ else { // Create button. if ($write_permisson) { echo ' '; - echo '
'; + echo ''; html_print_submit_button(__('Create'), 'create', false, 'class="sub next"'); echo ''; } @@ -559,7 +559,7 @@ $(document).ready (function () { if ( && ) { if (confirm("")) { - window.location.href = "index.php?sec=estado&sec2=godmode/agentes/planned_downtime.list&migrate_malformed=1"; + window.location.href = "index.php?sec=extensions&sec2=godmode/agentes/planned_downtime.list&migrate_malformed=1"; } } }); diff --git a/pandora_console/godmode/groups/credential_store.php b/pandora_console/godmode/groups/credential_store.php index 3273e1c038..46d1a929b7 100644 --- a/pandora_console/godmode/groups/credential_store.php +++ b/pandora_console/godmode/groups/credential_store.php @@ -29,599 +29,43 @@ // Begin. global $config; -// Check access. -check_login(); +require_once $config['homedir'].'/include/class/CredentialStore.class.php'; -if (! check_acl($config['id_user'], 0, 'PM')) { - db_pandora_audit( - 'ACL Violation', - 'Trying to access event viewer' - ); +$ajaxPage = 'godmode/groups/credential_store'; +// Control call flow. +try { + // User access and validation is being processed on class constructor. + $cs = new CredentialStore($ajaxPage); +} catch (Exception $e) { if (is_ajax()) { - return ['error' => 'noaccess']; + echo json_encode(['error' => '[CredentialStore]'.$e->getMessage() ]); + exit; + } else { + echo '[CredentialStore]'.$e->getMessage(); } - include 'general/noaccess.php'; + // Stop this execution, but continue 'globally'. return; } -// Required files. -ui_require_css_file('credential_store'); -require_once $config['homedir'].'/include/functions_credential_store.php'; -require_once $config['homedir'].'/include/functions_io.php'; - +// AJAX controller. if (is_ajax()) { - $draw = get_parameter('draw', 0); - $filter = get_parameter('filter', []); - $get_key = get_parameter('get_key', 0); - $new_form = get_parameter('new_form', 0); - $new_key = get_parameter('new_key', 0); - $update_key = get_parameter('update_key', 0); - $delete_key = get_parameter('delete_key', 0); + $method = get_parameter('method'); - if ($new_form) { - echo print_inputs(); - exit; - } - - if ($delete_key) { - $identifier = get_parameter('identifier', null); - - if (empty($identifier)) { - ajax_msg('error', __('identifier cannot be empty')); - } - - if (db_process_sql_delete( - 'tcredential_store', - ['identifier' => $identifier] - ) === false - ) { - ajax_msg('error', $config['dbconnection']->error, true); + if (method_exists($cs, $method) === true) { + if ($cs->ajaxMethod($method) === true) { + $cs->{$method}(); } else { - ajax_msg('result', $identifier, true); + $cs->error('Unavailable method.'); } + } else { + $cs->error('Method not found. ['.$method.']'); } - if ($update_key) { - $data = get_parameter('values', null); - - if ($data === null || !is_array($data)) { - echo json_encode(['error' => __('Invalid parameters, please retry')]); - exit; - } - - $values = []; - foreach ($data as $key => $value) { - if ($key == 'identifier') { - $identifier = base64_decode($value); - } else if ($key == 'product') { - $product = base64_decode($value); - } else { - $values[$key] = base64_decode($value); - } - } - - if (empty($identifier)) { - ajax_msg('error', __('identifier cannot be empty')); - } - - if (empty($product)) { - ajax_msg('error', __('product cannot be empty')); - } - - if (db_process_sql_update( - 'tcredential_store', - $values, - ['identifier' => $identifier] - ) === false - ) { - ajax_msg('error', $config['dbconnection']->error); - } else { - ajax_msg('result', $identifier); - } - - exit; - } - - if ($new_key) { - $data = get_parameter('values', null); - - if ($data === null || !is_array($data)) { - echo json_encode(['error' => __('Invalid parameters, please retry')]); - exit; - } - - $values = []; - foreach ($data as $key => $value) { - $values[$key] = base64_decode($value); - if ($key == 'identifier') { - $values[$key] = preg_replace('/\s+/', '-', trim($values[$key])); - } - } - - $identifier = $values['identifier']; - - if (empty($identifier)) { - ajax_msg('error', __('identifier cannot be empty')); - } - - if (empty($values['product'])) { - ajax_msg('error', __('product cannot be empty')); - } - - if (db_process_sql_insert('tcredential_store', $values) === false) { - ajax_msg('error', $config['dbconnection']->error); - } else { - ajax_msg('result', $identifier); - } - - exit; - } - - if ($get_key) { - $identifier = get_parameter('identifier', null); - - $key = get_key($identifier); - echo print_inputs($key); - - exit; - } - - if ($draw) { - // Datatables offset, limit and order. - $start = get_parameter('start', 0); - $length = get_parameter('length', $config['block_size']); - $order = get_datatable_order(true); - try { - ob_start(); - - $fields = [ - 'cs.*', - 'tg.nombre as `group`', - ]; - - // Retrieve data. - $data = credentials_get_all( - // Fields. - $fields, - // Filter. - $filter, - // Offset. - $start, - // Limit. - $length, - // Order. - $order['direction'], - // Sort field. - $order['field'] - ); - - // Retrieve counter. - $count = credentials_get_all( - 'count', - $filter - ); - - if ($data) { - $data = array_reduce( - $data, - function ($carry, $item) { - // Transforms array of arrays $data into an array - // of objects, making a post-process of certain fields. - $tmp = (object) $item; - $tmp->username = io_safe_output($tmp->username); - - if (empty($tmp->group)) { - $tmp->group = __('All'); - } else { - $tmp->group = io_safe_output($tmp->group); - } - - $carry[] = $tmp; - return $carry; - } - ); - } - - // Datatables format: RecordsTotal && recordsfiltered. - echo json_encode( - [ - 'data' => $data, - 'recordsTotal' => $count, - 'recordsFiltered' => $count, - ] - ); - // Capture output. - $response = ob_get_clean(); - } catch (Exception $e) { - return json_encode(['error' => $e->getMessage()]); - } - - // If not valid, show error with issue. - json_decode($response); - if (json_last_error() == JSON_ERROR_NONE) { - // If valid dump. - echo $response; - } else { - echo json_encode( - ['error' => $response] - ); - } - - - exit; - } - + // Stop any execution. exit; +} else { + // Run. + $cs->run(); } - -// Datatables list. -try { - $columns = [ - 'group', - 'identifier', - 'product', - 'username', - 'options', - ]; - - $column_names = [ - __('Group'), - __('Identifier'), - __('Product'), - __('User'), - [ - 'text' => __('Options'), - 'class' => 'action_buttons', - ], - ]; - - $table_id = 'keystore'; - // Load datatables user interface. - ui_print_datatable( - [ - 'id' => $table_id, - 'class' => 'info_table', - 'style' => 'width: 100%', - 'columns' => $columns, - 'column_names' => $column_names, - 'ajax_url' => 'godmode/groups/credential_store', - 'ajax_postprocess' => 'process_datatables_item(item)', - 'no_sortable_columns' => [-1], - 'order' => [ - 'field' => 'identifier', - 'direction' => 'asc', - ], - 'search_button_class' => 'sub filter float-right', - 'form' => [ - 'inputs' => [ - [ - 'label' => __('Group'), - 'type' => 'select', - 'id' => 'filter_id_group', - 'name' => 'filter_id_group', - 'options' => users_get_groups_for_select( - $config['id_user'], - 'AR', - true, - true, - false - ), - ], - [ - 'label' => __('Free search'), - 'type' => 'text', - 'class' => 'mw250px', - 'id' => 'free_search', - 'name' => 'free_search', - ], - ], - ], - ] - ); -} catch (Exception $e) { - echo $e->getMessage(); -} - -// Auxiliar div. -$new = ''; -$details = ''; -$aux = ''; - - -echo $new.$details.$aux; - -// Create button. -echo '
'; -html_print_submit_button( - __('Add key'), - 'create', - false, - 'class="sub next"' -); -echo '
'; - -?> - - diff --git a/pandora_console/godmode/massive/massive_edit_agents.php b/pandora_console/godmode/massive/massive_edit_agents.php index 9a43c661ce..83001be810 100755 --- a/pandora_console/godmode/massive/massive_edit_agents.php +++ b/pandora_console/godmode/massive/massive_edit_agents.php @@ -59,8 +59,10 @@ if ($update_agents) { $values['id_grupo'] = get_parameter('group'); } - if (get_parameter('interval', 0) != 0) { - $values['intervalo'] = get_parameter('interval'); + if (!(get_parameter('interval_select') == -1 && empty(get_parameter('interval_text')))) { + if (get_parameter('interval', 0) != 0) { + $values['intervalo'] = get_parameter('interval'); + } } if (get_parameter('id_os', '') != -1) { @@ -199,7 +201,7 @@ if ($update_agents) { } // Update the configuration files. - if ($result && ($old_interval_value != $values['intervalo'])) { + if ($result && ($old_interval_value != $values['intervalo']) && !empty($values['intervalo'])) { enterprise_hook( 'config_agents_update_config_token', [ @@ -523,7 +525,7 @@ $table->data[1][1] = html_print_select_groups(false, 'AR', false, 'group', $grou $table->data[2][0] = __('Interval'); -$table->data[2][1] = html_print_extended_select_for_time('interval', 0, '', __('No change'), '0', 10, true, 'width: 150px'); +$table->data[2][1] = html_print_extended_select_for_time('interval', 0, '', __('No change'), '0', 10, true, 'width: 150px', false); $table->data[3][0] = __('OS'); $table->data[3][1] = html_print_select_from_sql( diff --git a/pandora_console/godmode/menu.php b/pandora_console/godmode/menu.php index 000a105257..7175081912 100644 --- a/pandora_console/godmode/menu.php +++ b/pandora_console/godmode/menu.php @@ -21,27 +21,42 @@ require_once 'include/functions_menu.php'; $menu_godmode = []; $menu_godmode['class'] = 'godmode'; - -if (check_acl($config['id_user'], 0, 'PM')) { +if (check_acl($config['id_user'], 0, 'AR') + || check_acl($config['id_user'], 0, 'AW') + || check_acl($config['id_user'], 0, 'RR') + || check_acl($config['id_user'], 0, 'RW') + || check_acl($config['id_user'], 0, 'PM') +) { $sub = []; $sub['godmode/servers/discovery&wiz=main']['text'] = __('Main'); $sub['godmode/servers/discovery&wiz=main']['id'] = 'Discovery'; - $sub['godmode/servers/discovery&wiz=tasklist']['text'] = __('Task list'); $sub['godmode/servers/discovery&wiz=tasklist']['id'] = 'tasklist'; - $sub2 = []; - $sub2['godmode/servers/discovery&wiz=hd&mode=netscan']['text'] = __('Network scan'); - enterprise_hook('hostdevices_submenu'); - $sub2['godmode/servers/discovery&wiz=hd&mode=customnetscan']['text'] = __('Custom network scan'); - $sub2['godmode/servers/discovery&wiz=hd&mode=managenetscanscripts']['text'] = __('Manage scan scripts'); - $sub['godmode/servers/discovery&wiz=hd']['text'] = __('Host & devices'); - $sub['godmode/servers/discovery&wiz=hd']['id'] = 'hd'; - $sub['godmode/servers/discovery&wiz=hd']['sub2'] = $sub2; + if (check_acl($config['id_user'], 0, 'AW') + || check_acl($config['id_user'], 0, 'PM') + ) { + if (check_acl($config['id_user'], 0, 'AW')) { + $sub2 = []; + $sub2['godmode/servers/discovery&wiz=hd&mode=netscan']['text'] = __('Network scan'); + enterprise_hook('hostdevices_submenu'); + $sub2['godmode/servers/discovery&wiz=hd&mode=customnetscan']['text'] = __('Custom network scan'); + } - enterprise_hook('applications_menu'); - enterprise_hook('cloud_menu'); - enterprise_hook('console_task_menu'); + if (check_acl($config['id_user'], 0, 'PM')) { + $sub2['godmode/servers/discovery&wiz=hd&mode=managenetscanscripts']['text'] = __('Manage scan scripts'); + } + + $sub['godmode/servers/discovery&wiz=hd']['text'] = __('Host & devices'); + $sub['godmode/servers/discovery&wiz=hd']['id'] = 'hd'; + $sub['godmode/servers/discovery&wiz=hd']['sub2'] = $sub2; + } + + if (check_acl($config['id_user'], 0, 'AW')) { + enterprise_hook('applications_menu'); + enterprise_hook('cloud_menu'); + enterprise_hook('console_task_menu'); + } // Add to menu. $menu_godmode['discovery']['text'] = __('Discovery'); @@ -92,7 +107,7 @@ if (!empty($sub)) { } $sub = []; -if (check_acl($config['id_user'], 0, 'AW')) { +if (check_acl($config['id_user'], 0, 'PM')) { $sub['godmode/groups/group_list']['text'] = __('Manage agents groups'); $sub['godmode/groups/group_list']['id'] = 'Manage agents groups'; } @@ -295,6 +310,9 @@ if (check_acl($config['id_user'], 0, 'PM')) { $sub2['godmode/setup/setup&section=ehorus']['text'] = __('eHorus'); $sub2['godmode/setup/setup&section=ehorus']['refr'] = 0; + $sub2['godmode/setup/setup&section=integria']['text'] = __('Integria IMS'); + $sub2['godmode/setup/setup&section=integria']['refr'] = 0; + $sub2['godmode/setup/setup&section=notifications']['text'] = __('Notifications'); $sub2['godmode/setup/setup&section=notifications']['refr'] = 0; @@ -381,9 +399,6 @@ if (is_array($config['extensions'])) { if (strlen($extmenu['fatherId']) > 0) { if (array_key_exists('subfatherId', $extmenu)) { if (strlen($extmenu['subfatherId']) > 0) { - if ($extmenu['name'] = 'DB schema check') { - } - $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['subfatherId']]['sub2'][$extmenu['sec2']]['text'] = __($extmenu['name']); $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['subfatherId']]['sub2'][$extmenu['sec2']]['id'] = $extmenu['name']; $menu_godmode[$extmenu['fatherId']]['sub'][$extmenu['subfatherId']]['sub2'][$extmenu['sec2']]['refr'] = 0; diff --git a/pandora_console/godmode/reporting/graph_container.php b/pandora_console/godmode/reporting/graph_container.php index ccc3b6dde6..3b87fc63e3 100644 --- a/pandora_console/godmode/reporting/graph_container.php +++ b/pandora_console/godmode/reporting/graph_container.php @@ -16,10 +16,10 @@ global $config; // Check user credentials check_login(); -if (! check_acl($config['id_user'], 0, 'RR')) { +if (! check_acl($config['id_user'], 0, 'RR') || enterprise_installed() === false) { db_pandora_audit( 'ACL Violation', - 'Trying to access Inventory Module Management' + 'Trying to access Graph container' ); include 'general/noaccess.php'; return; diff --git a/pandora_console/godmode/reporting/graphs.php b/pandora_console/godmode/reporting/graphs.php index cb52af5e04..1fba644037 100644 --- a/pandora_console/godmode/reporting/graphs.php +++ b/pandora_console/godmode/reporting/graphs.php @@ -71,10 +71,12 @@ switch ($activeTab) { break; } -$buttons['graph_container'] = [ - 'active' => false, - 'text' => ''.html_print_image('images/graph-container.png', true, ['title' => __('Graphs containers')]).'', -]; +if ($enterpriseEnable) { + $buttons['graph_container'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/graph-container.png', true, ['title' => __('Graphs containers')]).'', + ]; +} $delete_graph = (bool) get_parameter('delete_graph'); $view_graph = (bool) get_parameter('view_graph'); @@ -257,11 +259,6 @@ $table_aux = new stdClass(); $table->cellspacing = 0; $table->align = []; $table->head = []; - if ($report_w || $report_m) { - $table->align[5] = 'left'; - $table->head[5] = html_print_checkbox('all_delete', 0, false, true, false); - $table->size[5] = '20px'; - } $table->head[0] = __('Graph name'); $table->head[1] = __('Description'); @@ -280,6 +277,12 @@ $table_aux = new stdClass(); $table->size[4] = '90px'; } + if ($report_w || $report_m) { + $table->align[5] = 'left'; + $table->head[5] = html_print_checkbox('all_delete', 0, false, true, false); + $table->size[5] = '20px'; + } + $table->data = []; $result_graphs = array_slice($graphs, $offset, $config['block_size']); @@ -287,10 +290,6 @@ $table_aux = new stdClass(); foreach ($result_graphs as $graph) { $data = []; - if ($report_m) { - $data[5] .= html_print_checkbox_extended('delete_multiple[]', $graph['id_graph'], false, false, '', 'class="check_delete" style="margin-left:2px;"', true); - } - $data[0] = ''.ui_print_truncate_text($graph['name'], 70).''; $data[1] = ui_print_truncate_text($graph['description'], 70); @@ -309,6 +308,10 @@ $table_aux = new stdClass(); return false;">'.html_print_image('images/cross.png', true, ['alt' => __('Delete'), 'title' => __('Delete')]).''; } + if ($report_m) { + $data[5] .= html_print_checkbox_extended('delete_multiple[]', $graph['id_graph'], false, false, '', 'class="check_delete" style="margin-left:2px;"', true); + } + array_push($table->data, $data); } diff --git a/pandora_console/godmode/reporting/reporting_builder.item_editor.php b/pandora_console/godmode/reporting/reporting_builder.item_editor.php index 798d03707d..e7201ab155 100755 --- a/pandora_console/godmode/reporting/reporting_builder.item_editor.php +++ b/pandora_console/godmode/reporting/reporting_builder.item_editor.php @@ -153,6 +153,7 @@ $checks_in_ok_status = true; $unknown_checks = true; $agent_max_value = true; $agent_min_value = true; +$uncompressed_module = true; switch ($action) { case 'new': @@ -232,12 +233,14 @@ switch ($action) { $style = json_decode(io_safe_output($item['style']), true); + $name_from_template = $style['name_label']; + $show_in_same_row = $style['show_in_same_row']; $show_in_landscape = $style['show_in_landscape']; $hide_notinit_agents = $style['hide_notinit_agents']; $dyn_height = $style['dyn_height']; $type = $item['type']; - $name = $item['name']; + $name = $style['name_label']; switch ($type) { case 'event_report_log': @@ -427,6 +430,7 @@ switch ($action) { ); $idAgentModule = $item['id_agent_module']; $period = $item['period']; + $uncompressed_module = $item['uncompressed_module']; break; case 'historical_data': @@ -478,50 +482,6 @@ switch ($action) { $period = $item['period']; break; - case 'TTRT': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter( - 'id_agente', - 'tagente_modulo', - ['id_agente_modulo' => $idAgentModule] - ); - $period = $item['period']; - break; - - case 'TTO': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter( - 'id_agente', - 'tagente_modulo', - ['id_agente_modulo' => $idAgentModule] - ); - $period = $item['period']; - break; - - case 'MTBF': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter( - 'id_agente', - 'tagente_modulo', - ['id_agente_modulo' => $idAgentModule] - ); - $period = $item['period']; - break; - - case 'MTTR': - $description = $item['description']; - $idAgentModule = $item['id_agent_module']; - $idAgent = db_get_value_filter( - 'id_agente', - 'tagente_modulo', - ['id_agente_modulo' => $idAgentModule] - ); - $period = $item['period']; - break; - case 'alert_report_module': $description = $item['description']; $idAgentModule = $item['id_agent_module']; @@ -786,10 +746,6 @@ switch ($action) { case 'avg_value': case 'projection_graph': case 'prediction_date': - case 'TTRT': - case 'TTO': - case 'MTBF': - case 'MTTR': case 'simple_baseline_graph': case 'event_report_log': case 'increment': @@ -810,7 +766,6 @@ switch ($action) { break; } - $urlForm = $config['homeurl'].'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder&tab=item_editor&action='.$actionParameter.'&id_report='.$idReport; echo '
'; @@ -868,18 +823,33 @@ $class = 'databox filters';
@@ -1565,10 +1535,8 @@ $class = 'databox filters'; $all_modules = ''; } else { $all_modules = db_get_all_rows_sql( - 'SELECT DISTINCT nombre, id_agente_modulo - FROM tagente_modulo - WHERE id_agente - IN ('.implode(',', array_values($id_agents)).')' + 'SELECT DISTINCT nombre FROM + tagente_modulo WHERE id_agente IN ('.implode(',', array_values($id_agents)).')' ); } @@ -2794,6 +2762,23 @@ $class = 'databox filters'; ?> + + + + + +
+ + + +
@@ -3529,6 +3514,9 @@ $(document).ready (function () { $("#id_agents").change(agent_changed_by_multiple_agents); + // Load selected modules by default + $("#id_agents2").trigger('click'); + $("#combo_group").change ( function () { jQuery.post ("ajax.php", @@ -3719,10 +3707,6 @@ $(document).ready (function () { case 'event_report_module': case 'simple_graph': case 'simple_baseline_graph': - case 'TTRT': - case 'TTO': - case 'MTBF': - case 'MTTR': case 'prediction_date': case 'projection_graph': case 'avg_value': @@ -3760,10 +3744,6 @@ $(document).ready (function () { case 'event_report_module': case 'simple_graph': case 'simple_baseline_graph': - case 'TTRT': - case 'TTO': - case 'MTBF': - case 'MTTR': case 'prediction_date': case 'projection_graph': case 'avg_value': @@ -4523,6 +4503,7 @@ function chooseType() { $('#row_select_fields').hide(); $("#row_select_fields2").hide(); $("#row_select_fields3").hide(); + $("#row_uncompressed_module").hide(); // SLA list default state. $("#sla_list").hide(); @@ -4731,6 +4712,7 @@ function chooseType() { $("#row_module").show(); $("#row_period").show(); $("#row_historical_db_check").hide(); + $("#row_uncompressed_module").show(); break; case 'historical_data': @@ -4794,38 +4776,6 @@ function chooseType() { $("#row_historical_db_check").hide(); break; - case 'TTRT': - $("#row_description").show(); - $("#row_agent").show(); - $("#row_module").show(); - $("#row_period").show(); - $("#row_historical_db_check").hide(); - break; - - case 'TTO': - $("#row_description").show(); - $("#row_agent").show(); - $("#row_module").show(); - $("#row_period").show(); - $("#row_historical_db_check").hide(); - break; - - case 'MTBF': - $("#row_description").show(); - $("#row_agent").show(); - $("#row_module").show(); - $("#row_period").show(); - $("#row_historical_db_check").hide(); - break; - - case 'MTTR': - $("#row_description").show(); - $("#row_agent").show(); - $("#row_module").show(); - $("#row_period").show(); - $("#row_historical_db_check").hide(); - break; - case 'alert_report_module': $("#row_description").show(); $("#row_agent").show(); @@ -5178,10 +5128,6 @@ function chooseType() { case 'min_value': case 'max_value': case 'avg_value': - case 'TTRT': - case 'TTO': - case 'MTBF': - case 'MTTR': case 'simple_baseline_graph': $("#row_label").show(); break; diff --git a/pandora_console/godmode/reporting/reporting_builder.list_items.php b/pandora_console/godmode/reporting/reporting_builder.list_items.php index 00c6fa245a..1b7d3b4df6 100755 --- a/pandora_console/godmode/reporting/reporting_builder.list_items.php +++ b/pandora_console/godmode/reporting/reporting_builder.list_items.php @@ -1,18 +1,34 @@ data[0][1] .= html_print_select($modules, 'module_filter', $moduleFilter, '', __('All'), 0, true); $table->data[0][2] = __('Type'); $table->data[0][2] .= html_print_select($types, 'type_filter', $typeFilter, '', __('All'), 0, true); - // $table->data[1][2] = $table->data[1][3] = ''; $form = ''; $form .= html_print_table($table, true); $form .= '
'; @@ -265,13 +291,6 @@ if ($moduleFilter != 0) { $where .= ' AND id_agent_module = '.$moduleFilter; } -// Filter report items created from metaconsole in normal console list and the opposite -if (defined('METACONSOLE') and $config['metaconsole'] == 1) { - $where .= ' AND ((server_name IS NOT NULL AND length(server_name) != 0) '.'OR '.$type_escaped.' IN (\'general\', \'SLA\', \'exception\', \'availability\', \'availability_graph\', \'top_n\',\'SLA_monthly\',\'SLA_weekly\',\'SLA_hourly\',\'text\'))'; -} else { - $where .= ' AND ((server_name IS NULL OR length(server_name) = 0) '.'OR '.$type_escaped.' IN (\'general\', \'SLA\', \'exception\', \'availability\', \'top_n\'))'; -} - switch ($config['dbtype']) { case 'mysql': $items = db_get_all_rows_sql( @@ -306,13 +325,17 @@ switch ($config['dbtype']) { 'AND', false ); - // Delete rnum row generated by oracle_recode_query() function + // Delete rnum row generated by oracle_recode_query() function. if ($items !== false) { for ($i = 0; $i < count($items); $i++) { unset($items[$i]['rnum']); } } break; + + default: + // Default. + break; } $countItems = db_get_sql( @@ -421,29 +444,30 @@ foreach ($items as $item) { $row[1] = get_report_name($item['type']); - if ($item['type'] == 'custom_graph') { - $custom_graph_name = db_get_row_sql('select name from tgraph where id_graph = '.$item['id_gs']); - $row[1] = get_report_name($item['type']).' ('.$custom_graph_name['name'].')'; - } - $server_name = $item['server_name']; - if (($config['metaconsole'] == 1) && ($server_name != '') && defined('METACONSOLE')) { + if (is_metaconsole()) { $connection = metaconsole_get_connection($server_name); if (metaconsole_load_external_db($connection) != NOERR) { // ui_print_error_message ("Error connecting to ".$server_name); } } + if ($item['type'] == 'custom_graph') { + $custom_graph_name = db_get_row_sql('SELECT name FROM tgraph WHERE id_graph = '.$item['id_gs']); + $row[1] = get_report_name($item['type']).' ('.$custom_graph_name['name'].')'; + } + + if ($item['id_agent'] == 0) { $is_inventory_item = $item['type'] == 'inventory' || $item['type'] == 'inventory_changes'; - // Due to SLA or top N or general report items + // Due to SLA or top N or general report items. if (!$is_inventory_item && ($item['id_agent_module'] == '' || $item['id_agent_module'] == 0)) { $row[2] = ''; $row[3] = ''; } else { - // The inventory items have the agents and modules in json format in the field external_source + // The inventory items have the agents and modules in json format in the field external_source. if ($is_inventory_item) { $external_source = json_decode($item['external_source'], true); $agents = $external_source['id_agents']; @@ -489,11 +513,18 @@ foreach ($items as $item) { $row[4] = '-'; } - if ($item['name'] == '' && $item['description'] == '') { - $row[5] = '-'; - } else { - $text = empty($item['name']) ? $item['description'] : $item['name']; + $style = json_decode(io_safe_output($item['style']), true); + + if ($style['name_label'] != '') { + $text = empty($style['name_label']) ? $item['description'] : $style['name_label']; $row[5] = ui_print_truncate_text($text, 'description', true, true); + } else { + if ($item['name'] == '' && $item['description'] == '') { + $row[5] = '-'; + } else { + $text = empty($item['name']) ? $item['description'] : $item['name']; + $row[5] = ui_print_truncate_text($text, 'description', true, true); + } } $row[6] = ''; @@ -515,7 +546,7 @@ foreach ($items as $item) { $table->data[] = $row; $count++; - // Restore db connection + // Restore db connection. if (($config['metaconsole'] == 1) && ($server_name != '') && defined('METACONSOLE')) { metaconsole_restore_db(); } diff --git a/pandora_console/godmode/reporting/reporting_builder.php b/pandora_console/godmode/reporting/reporting_builder.php index aa89496ef7..823713877b 100755 --- a/pandora_console/godmode/reporting/reporting_builder.php +++ b/pandora_console/godmode/reporting/reporting_builder.php @@ -1908,6 +1908,11 @@ switch ($action) { $values['id_agent'] = get_parameter('group'); } + if ($values['type'] == 'sumatory') { + $values['uncompressed_module'] = get_parameter('uncompressed_module', 0); + } + + $values['header_definition'] = get_parameter('header'); $values['column_separator'] = get_parameter('field'); $values['line_separator'] = get_parameter('line'); @@ -2001,10 +2006,6 @@ switch ($action) { case 'avg_value': case 'projection_graph': case 'prediction_date': - case 'TTRT': - case 'TTO': - case 'MTBF': - case 'MTTR': case 'simple_baseline_graph': case 'nt_top_n': if ($label != '') { @@ -2464,6 +2465,10 @@ switch ($action) { $values['id_agent'] = get_parameter('group'); } + if ($values['type'] == 'sumatory') { + $values['uncompressed_module'] = get_parameter('uncompressed_module', 0); + } + $values['header_definition'] = get_parameter('header'); $values['column_separator'] = get_parameter('field'); $values['line_separator'] = get_parameter('line'); @@ -2603,10 +2608,6 @@ switch ($action) { case 'avg_value': case 'projection_graph': case 'prediction_date': - case 'TTRT': - case 'TTO': - case 'MTBF': - case 'MTTR': case 'simple_baseline_graph': case 'nt_top_n': if ($label != '') { @@ -3133,17 +3134,19 @@ if ($enterpriseEnable && defined('METACONSOLE')) { break; } - ui_print_page_header( - $textReportName, - 'images/op_reporting.png', - false, - $helpers, - false, - $buttons, - false, - '', - 60 - ); + if ($action !== 'update' && !is_metaconsole()) { + ui_print_page_header( + $textReportName, + 'images/op_reporting.png', + false, + $helpers, + false, + $buttons, + false, + '', + 60 + ); + } } if ($resultOperationDB !== null) { @@ -3165,6 +3168,26 @@ if ($resultOperationDB !== null) { __('Successfull action'), __('Unsuccessful action

'.$err) ); + + if ($action == 'update') { + $buttons[$activeTab]['active'] = false; + $activeTab = 'list_items'; + $buttons[$activeTab]['active'] = true; + + if (!is_metaconsole()) { + ui_print_page_header( + $textReportName, + 'images/op_reporting.png', + false, + $helpers, + false, + $buttons, + false, + '', + 60 + ); + } + } } switch ($activeTab) { diff --git a/pandora_console/godmode/servers/discovery.php b/pandora_console/godmode/servers/discovery.php index 3f2166bb39..2d0fcec8a1 100755 --- a/pandora_console/godmode/servers/discovery.php +++ b/pandora_console/godmode/servers/discovery.php @@ -4,7 +4,14 @@ global $config; check_login(); -if (! check_acl($config['id_user'], 0, 'AW')) { +if (! check_acl($config['id_user'], 0, 'AR') + && ! check_acl($config['id_user'], 0, 'AW') + && ! check_acl($config['id_user'], 0, 'AM') + && ! check_acl($config['id_user'], 0, 'RR') + && ! check_acl($config['id_user'], 0, 'RW') + && ! check_acl($config['id_user'], 0, 'RM') + && ! check_acl($config['id_user'], 0, 'PM') +) { db_pandora_audit( 'ACL Violation', 'Trying to access Server Management' @@ -134,11 +141,18 @@ if ($classname_selected === null) { $classname = basename($classpath, '.class.php'); $obj = new $classname(); + $button = $obj->load(); + + if ($button === false) { + // No acess, skip. + continue; + } + // DiscoveryTaskList must be first button. if ($classname == 'DiscoveryTaskList') { - array_unshift($wiz_data, $obj->load()); + array_unshift($wiz_data, $button); } else { - $wiz_data[] = $obj->load(); + $wiz_data[] = $button; } } diff --git a/pandora_console/godmode/servers/plugin.php b/pandora_console/godmode/servers/plugin.php index 3eb385332c..79fcfc61a2 100644 --- a/pandora_console/godmode/servers/plugin.php +++ b/pandora_console/godmode/servers/plugin.php @@ -928,10 +928,10 @@ if (($create != '') || ($view != '')) { $other['plugin_type'] = $plugin_meta['plugin_type']; $other['macros'] = urlencode($plugin_meta['macros']); $other['parameters'] = urlencode($plugin_meta['parameters']); - $other = implode('%7C', $other); + $other = implode('%7E', $other); $auth_token = json_decode($value['auth_token']); - $url = $value['server_url'].'include/api.php?op=set&op2=push_plugin'.'&id='.$pluginid.'&other_mode=url_encode_separator_%7C&other='.$other."&apipass=$auth_token->api_password"."&user=$auth_token->console_user&pass=$auth_token->console_password"; + $url = $value['server_url'].'include/api.php?op=set&op2=push_plugin'.'&id='.$pluginid.'&other_mode=url_encode_separator_%7E&other='.$other."&apipass=$auth_token->api_password"."&user=$auth_token->console_user&pass=$auth_token->console_password"; $file_path = realpath($plugin_meta['execute']); $post = ''; if (file_exists($file_path)) { diff --git a/pandora_console/godmode/setup/license.php b/pandora_console/godmode/setup/license.php index 06d7d2e7e3..c459cdb39f 100644 --- a/pandora_console/godmode/setup/license.php +++ b/pandora_console/godmode/setup/license.php @@ -107,7 +107,7 @@ $table->data = []; $table->data[0][0] = ''.__('Customer key').''; $table->data[0][1] = html_print_textarea('keys[customer_key]', 10, 255, $settings->customer_key, 'style="height:50px; width:450px;"', true); -$table->data[1][0] = ''.__('Expires').''; +$table->data[1][0] = ''.__($license['expiry_caption']).''; $table->data[1][1] = html_print_input_text('expires', $license['expiry_date'], '', 10, 255, true, true); $table->data[2][0] = ''.__('Platform Limit').''; diff --git a/pandora_console/godmode/setup/setup.php b/pandora_console/godmode/setup/setup.php index c32f128ddd..a46d7bc832 100644 --- a/pandora_console/godmode/setup/setup.php +++ b/pandora_console/godmode/setup/setup.php @@ -117,6 +117,11 @@ if (check_acl($config['id_user'], 0, 'AW')) { } } +$buttons['integria'] = [ + 'active' => false, + 'text' => ''.html_print_image('images/integria.png', true, ['title' => __('Integria IMS')]).'', +]; + $buttons['ehorus'] = [ 'active' => false, 'text' => ''.html_print_image('images/ehorus/ehorus.png', true, ['title' => __('eHorus')]).'', @@ -167,6 +172,12 @@ switch ($section) { $help_header = 'setup_ehorus_tab'; break; + case 'integria': + $buttons['integria']['active'] = true; + $subpage = ' » '.__('Integria IMS'); + $help_header = 'setup_integria_tab'; + break; + case 'notifications': $buttons['notifications']['active'] = true; $subpage = ' » '.__('Notifications'); @@ -228,6 +239,10 @@ switch ($section) { include_once $config['homedir'].'/godmode/setup/setup_ehorus.php'; break; + case 'integria': + include_once $config['homedir'].'/godmode/setup/setup_integria.php'; + break; + case 'notifications': include_once $config['homedir'].'/godmode/setup/setup_notifications.php'; break; diff --git a/pandora_console/godmode/setup/setup_general.php b/pandora_console/godmode/setup/setup_general.php index ab1d1ef269..1385a9f193 100644 --- a/pandora_console/godmode/setup/setup_general.php +++ b/pandora_console/godmode/setup/setup_general.php @@ -58,6 +58,16 @@ global $config; check_login(); +if (is_ajax()) { + enterprise_include_once('include/functions_cron.php'); + + $test_address = get_parameter('test_address', ''); + + $res = enterprise_hook('send_email_attachment', [$test_address, __('This is an email test sent from Pandora FMS. If you can read this, your configuration works.'), __('Testing Pandora FMS email'), null]); + + echo $res; +} + $table = new StdClass(); $table->class = 'databox filters'; $table->id = 'setup_general'; @@ -68,6 +78,12 @@ $table->size[0] = '30%'; $table->style[0] = 'font-weight:bold'; $table->size[1] = '70%'; +$table_mail_conf = new stdClass(); +$table_mail_conf->width = '100%'; +$table_mail_conf->class = 'databox filters'; +$table_mail_conf->data = []; +$table_mail_conf->style[0] = 'font-weight: bold'; + // Current config["language"] could be set by user, not taken from global setup ! $current_system_lang = db_get_sql( 'SELECT `value` FROM tconfig WHERE `token` = "language"' @@ -330,6 +346,49 @@ echo ''.__('General options').''; html_print_input_hidden('update_config', 1); html_print_table($table); +$encryption = [ + 'ssl' => 'SSL/TLS', + 'sslv2' => 'SSLv2', + 'sslv3' => 'SSLv3', + 'tls' => 'STARTTLS', +]; + +echo ''; + +echo '
'; +echo ''.__('Mail configuration').''; + +$table_mail_conf->data[0][0] = __('From address'); +$table_mail_conf->data[0][1] = html_print_input_text('email_from_dir', $config['email_from_dir'], '', 30, 100, true); + +$table_mail_conf->data[1][0] = __('From name'); +$table_mail_conf->data[1][2] = html_print_input_text('email_from_name', $config['email_from_name'], '', 30, 100, true); + +$table_mail_conf->data[2][0] = __('SMTP Server'); +$table_mail_conf->data[2][1] = html_print_input_text('email_smtpServer', $config['email_smtpServer'], '', 30, 100, true); + +$table_mail_conf->data[3][0] = __('SMTP Port'); +$table_mail_conf->data[3][1] = html_print_input_text('email_smtpPort', $config['email_smtpPort'], '', 30, 100, true); + +$table_mail_conf->data[4][0] = __('Encryption'); +$table_mail_conf->data[4][1] = html_print_select($encryption, 'email_encryption', $config['email_encryption'], '', __('none'), 0, true); + +$table_mail_conf->data[5][0] = __('Email user'); +$table_mail_conf->data[5][1] = html_print_input_text('email_username', $config['email_username'], '', 30, 100, true); + +$table_mail_conf->data[6][0] = __('Email password'); +$table_mail_conf->data[6][1] = html_print_input_password('email_password', io_output_password($config['email_password']), '', 30, 100, true); + +$uniqid = uniqid(); + +$table_mail_conf->data[7][0] = html_print_button(__('Email test'), 'email_test_dialog', false, "show_email_test('$uniqid');", 'class="sub next"', true).ui_print_help_tip(__('Check the current saved email configuration by sending a test email to a desired account.'), true); + +print_email_test_modal_window($uniqid); + +html_print_input_hidden('update_config', 1); +html_print_table($table_mail_conf); + + echo '
'; echo '
'; @@ -337,6 +396,25 @@ html_print_submit_button(__('Update'), 'update_button', false, 'class="sub upd"' echo '
'; echo ''; +// Print the modal window for the summary of each alerts group +function print_email_test_modal_window($id) +{ + // Email config table. + $table_mail_test = new stdClass(); + $table_mail_test->width = '100%'; + $table_mail_test->class = 'databox filters'; + $table_mail_test->data = []; + $table_mail_test->style[0] = 'font-weight: bold'; + $table_mail_test->colspan[1][0] = 2; + + $table_mail_test->data[0][0] = __('Address').ui_print_help_tip(__('Email address to which the test email will be sent. Please check your inbox after email is sent.'), true); + $table_mail_test->data[0][1] = html_print_input_text('email_test_address', '', '', 40, 100, true); + + $table_mail_test->data[1][0] = html_print_button(__('Send'), 'email_test', false, '', 'class="sub next"', true).'  '; + + echo ''; +} + ?> diff --git a/pandora_console/godmode/setup/setup_integria.php b/pandora_console/godmode/setup/setup_integria.php new file mode 100644 index 0000000000..3ce6cf334c --- /dev/null +++ b/pandora_console/godmode/setup/setup_integria.php @@ -0,0 +1,702 @@ + 1]); + } else { + echo json_encode(['login' => 0]); + } + + return; +} + +$has_connection = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'get_login', []); + +if ($has_connection === false && $config['integria_enabled']) { + ui_print_error_message(__('Integria IMS API is not reachable')); +} + +if (get_parameter('update_config', 0) == 1) { + // Try to retrieve event response 'Create incident in IntegriaIMS from event' to check if it exists. + $event_response_exists = db_get_row_filter('tevent_response', ['name' => io_safe_input('Create ticket in IntegriaIMS from event')]); + + // Try to retrieve command 'Integia IMS Ticket' to check if it exists. + $command_exists = db_get_row_filter('talert_commands', ['name' => io_safe_input('Integria IMS Ticket')]); + + if ($config['integria_enabled'] == 1) { + if ($event_response_exists === false) { + // Create 'Create incident in IntegriaIMS from event' event response only when user enables IntegriaIMS integration and it does not exist in database. + db_process_sql_insert( + 'tevent_response', + [ + 'name' => io_safe_input('Create ticket in IntegriaIMS from event'), + 'description' => io_safe_input('Create a ticket in Integria IMS from an event'), + 'target' => io_safe_input('index.php?sec=incident&sec2=operation/incidents/configure_integriaims_incident&from_event=_event_id_'), + 'type' => 'url', + 'id_group' => '0', + 'modal_width' => '0', + 'modal_height' => '0', + 'new_window' => '1', + 'params' => '', + 'server_to_exec' => '0', + ] + ); + } + + if ($command_exists === false) { + // Create 'Integria IMS Ticket' command only when user enables IntegriaIMS integration and it does not exist in database. + $id_command_inserted = db_process_sql_insert( + 'talert_commands', + [ + 'name' => io_safe_input('Integria IMS Ticket'), + 'command' => io_safe_input('Internal type'), + 'internal' => 1, + 'description' => io_safe_input('Create a ticket in Integria IMS'), + 'fields_descriptions' => '["'.io_safe_input('Ticket title').'","'.io_safe_input('Ticket group ID').'","'.io_safe_input('Ticket priority').'","'.io_safe_input('Ticket owner').'","'.io_safe_input('Ticket type').'","'.io_safe_input('Ticket status').'","'.io_safe_input('Ticket description').'"]', + ] + ); + + // Create 'Create Integria IMS Ticket' action only when user enables IntegriaIMS integration and command exists in database. + $action_values = [ + 'field1' => io_safe_input($config['incident_title']), + 'field1_recovery' => io_safe_input($config['incident_title']), + 'field2' => io_safe_input($config['default_group']), + 'field2_recovery' => io_safe_input($config['default_group']), + 'field3' => io_safe_input($config['default_criticity']), + 'field3_recovery' => io_safe_input($config['default_criticity']), + 'field4' => io_safe_input($config['default_owner']), + 'field4_recovery' => io_safe_input($config['default_owner']), + 'field5' => io_safe_input($config['incident_type']), + 'field5_recovery' => io_safe_input($config['incident_type']), + 'field6' => io_safe_input($config['incident_status']), + 'field6_recovery' => io_safe_input($config['incident_status']), + 'field7' => io_safe_input($config['incident_content']), + 'field7_recovery' => io_safe_input($config['incident_content']), + 'id_group' => 0, + 'action_threshold' => 0, + ]; + + alerts_create_alert_action(io_safe_input('Create Integria IMS ticket'), $id_command_inserted, $action_values); + } else { + // Update 'Create Integria IMS Ticket' action when setup data is updated, user enables IntegriaIMS integration and command does exist in database. + db_process_sql_update( + 'talert_actions', + [ + 'field1' => io_safe_input($config['incident_title']), + 'field1_recovery' => io_safe_input($config['incident_title']), + 'field2' => io_safe_input($config['default_group']), + 'field2_recovery' => io_safe_input($config['default_group']), + 'field3' => io_safe_input($config['default_criticity']), + 'field3_recovery' => io_safe_input($config['default_criticity']), + 'field4' => io_safe_input($config['default_owner']), + 'field4_recovery' => io_safe_input($config['default_owner']), + 'field5' => io_safe_input($config['incident_type']), + 'field5_recovery' => io_safe_input($config['incident_type']), + 'field6' => io_safe_input($config['incident_status']), + 'field6_recovery' => io_safe_input($config['incident_status']), + 'field7' => io_safe_input($config['incident_content']), + 'field7_recovery' => io_safe_input($config['incident_content']), + ], + ['name' => io_safe_input('Create Integria IMS ticket')] + ); + } + } else { + if ($event_response_exists != false) { + // Delete 'Create incident in IntegriaIMS from event' event response if it does exist and IntegriaIMS integration is disabled. + db_process_sql_delete('tevent_response', ['name' => io_safe_input('Create ticket in IntegriaIMS from event')]); + } + + if ($command_exists != false) { + // Delete 'Integria IMS Ticket' command if it does exist and IntegriaIMS integration is disabled. + db_process_sql_delete('talert_commands', ['name' => io_safe_input('Integria IMS Ticket')]); + + // Delete 'Create Integria IMS Ticket' action if command exists and IntegriaIMS integration is disabled. + db_process_sql_delete('talert_actions', ['name' => io_safe_input('Create Integria IMS ticket')]); + } + } +} + +// Get parameters from Integria IMS API. +$integria_group_values = []; +$integria_criticity_values = []; +$integria_users_values = []; +$integria_types_values = []; +$integria_status_values = []; + +$integria_groups_csv = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'get_groups', []); + +get_array_from_csv_data_pair($integria_groups_csv, $integria_group_values); + +$integria_status_csv = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'get_incidents_status', []); + +get_array_from_csv_data_pair($integria_status_csv, $integria_status_values); + +$integria_criticity_levels_csv = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'get_incident_priorities', []); + +get_array_from_csv_data_pair($integria_criticity_levels_csv, $integria_criticity_values); + +$integria_users_csv = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'get_users', []); + +$csv_array = explode("\n", $integria_users_csv); + +foreach ($csv_array as $csv_line) { + if (!empty($csv_line)) { + $integria_users_values[$csv_line] = $csv_line; + } +} + +$integria_types_csv = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'get_types', []); + +get_array_from_csv_data_pair($integria_types_csv, $integria_types_values); + +// Enable table. +$table_enable = new StdClass(); +$table_enable->data = []; +$table_enable->width = '100%'; +$table_enable->id = 'integria-enable-setup'; +$table_enable->class = 'databox filters'; +$table_enable->size['name'] = '30%'; +$table_enable->style['name'] = 'font-weight: bold'; + +// Enable Integria. +$row = []; +$row['name'] = __('Enable Integria IMS'); +$row['control'] = html_print_checkbox_switch('integria_enabled', 1, $config['integria_enabled'], true); +$table_enable->data['integria_enabled'] = $row; + +// Remote config table. +$table_remote = new StdClass(); +$table_remote->data = []; +$table_remote->width = '100%'; +$table_remote->styleTable = 'margin-bottom: 10px;'; +$table_remote->id = 'integria-remote-setup'; +$table_remote->class = 'databox filters'; +$table_remote->size['name'] = '30%'; +$table_remote->style['name'] = 'font-weight: bold'; + +// Integria user. +$row = []; +$row['name'] = __('User'); +$row['control'] = html_print_input_text('integria_user', $config['integria_user'], '', 30, 100, true); +$table_remote->data['integria_user'] = $row; + +// Integria password. +$row = []; +$row['name'] = __('Password'); +$row['control'] = html_print_input_password('integria_pass', io_output_password($config['integria_pass']), '', 30, 100, true); +$table_remote->data['integria_pass'] = $row; + +// Integria hostname. +$row = []; +$row['name'] = __('API Hostname'); +$row['control'] = html_print_input_text('integria_hostname', $config['integria_hostname'], '', 30, 100, true); +$row['control'] .= ui_print_help_tip(__('Hostname of Integria IMS\' API (scheme must be specified. Example: http://192.168.0.0)'), true); +$table_remote->data['integria_hostname'] = $row; + +// API password. +$row = []; +$row['name'] = __('API Password'); +$row['control'] = html_print_input_password('integria_api_pass', io_output_password($config['integria_api_pass']), '', 30, 100, true); +$row['control'] .= ui_print_help_tip(__('Password of Integria IMS\' API'), true); +$table_remote->data['integria_api_pass'] = $row; + +// Request timeout. +$row = []; +$row['name'] = __('Request timeout'); +$row['control'] = html_print_input_text('integria_req_timeout', $config['integria_req_timeout'], '', 3, 10, true); +$row['control'] .= ui_print_help_tip(__('Time in seconds to set the maximum time of the requests to the Integria API').'. '.__('0 to disable'), true); +$table_remote->data['integria_req_timeout'] = $row; + +// Alert settings. +$table_alert_settings = new StdClass(); +$table_alert_settings->data = []; +$table_alert_settings->width = '100%'; +$table_alert_settings->styleTable = 'margin-bottom: 10px;'; +$table_alert_settings->id = 'integria-cr-settings-setup'; +$table_alert_settings->class = 'databox filters'; +$table_alert_settings->size['name'] = '30%'; +$table_alert_settings->style['name'] = 'font-weight: bold'; + +// Alert incident title. +$row = []; +$row['name'] = __('Title'); +$row['control'] = html_print_input_text( + 'incident_title', + $config['incident_title'], + __('Name'), + 50, + 100, + true, + false, + false +).ui_print_help_icon('alert_macros', true); +$table_alert_settings->data['custom_response_incident_title'] = $row; + +// Alert incident description. +$row = []; +$row['name'] = __('Description'); +$row['control'] = html_print_input_text( + 'incident_content', + $config['incident_content'], + '', + 50, + 100, + true, + false, + false +).ui_print_help_icon('alert_macros', true); +$table_alert_settings->data['custom_response_incident_content'] = $row; + +// Alert default group. +$row = []; +$row['name'] = __('Group'); +$row['control'] = html_print_select( + $integria_group_values, + 'default_group', + $config['default_group'], + '', + __('Select'), + 0, + true, + false, + true, + '', + false +); +$table_alert_settings->data['custom_response_def_group'] = $row; + +// Alert default criticity. +$row = []; +$row['name'] = __('Priority'); +$row['control'] = html_print_select( + $integria_criticity_values, + 'default_criticity', + $config['default_criticity'], + '', + __('Select'), + 0, + true, + false, + true, + '', + false +); +$table_alert_settings->data['custom_response_def_criticity'] = $row; + +// Alert default owner. +$row = []; +$row['name'] = __('Owner'); +$row['control'] = html_print_autocomplete_users_from_integria( + 'default_owner', + $config['default_owner'], + true +); + +$table_alert_settings->data['custom_response_def_owner'] = $row; + +// Alert default incident type. +$row = []; +$row['name'] = __('Type'); +$row['control'] = html_print_select( + $integria_types_values, + 'incident_type', + $config['incident_type'], + '', + __('Select'), + 0, + true, + false, + true, + '', + false +); +$table_alert_settings->data['custom_response_incident_type'] = $row; + +// Alert default incident status. +$row = []; +$row['name'] = __('Status'); +$row['control'] = html_print_select( + $integria_status_values, + 'incident_status', + $config['incident_status'], + '', + __('Select'), + 0, + true, + false, + true, + '', + false +); +$table_alert_settings->data['custom_response_incident_status'] = $row; + +// Custom response settings. +$table_cr_settings = new StdClass(); +$table_cr_settings->data = []; +$table_cr_settings->width = '100%'; +$table_cr_settings->styleTable = 'margin-bottom: 10px;'; +$table_cr_settings->id = 'integria-cr-settings-setup'; +$table_cr_settings->class = 'databox filters'; +$table_cr_settings->size['name'] = '30%'; +$table_cr_settings->style['name'] = 'font-weight: bold'; + +// Custom response incident title. +$row = []; +$row['name'] = __('Title'); +$row['control'] = html_print_input_text( + 'cr_incident_title', + $config['cr_incident_title'], + __('Name'), + 50, + 100, + true, + false, + false +).ui_print_help_icon('response_macros', true); +$table_cr_settings->data['custom_response_incident_title'] = $row; + +// Custom response incident description. +$row = []; +$row['name'] = __('Description'); +$row['control'] = html_print_input_text( + 'cr_incident_content', + $config['cr_incident_content'], + '', + 50, + 100, + true, + false, + false +).ui_print_help_icon('response_macros', true); +$table_cr_settings->data['custom_response_incident_content'] = $row; + +// Custom response default group. +$row = []; +$row['name'] = __('Group'); +$row['control'] = html_print_select( + $integria_group_values, + 'cr_default_group', + $config['cr_default_group'], + '', + __('Select'), + 0, + true, + false, + true, + '', + false +); +$table_cr_settings->data['custom_response_def_group'] = $row; + +// Custom response default criticity. +$row = []; +$row['name'] = __('Priority'); +$row['control'] = html_print_select( + $integria_criticity_values, + 'cr_default_criticity', + $config['cr_default_criticity'], + '', + __('Select'), + 0, + true, + false, + true, + '', + false +); +$table_cr_settings->data['custom_response_def_criticity'] = $row; + +// Custom response default owner. +$row = []; +$row['name'] = __('Owner'); +$row['control'] = html_print_autocomplete_users_from_integria( + 'cr_default_owner', + $config['cr_default_owner'], + true +); + +$table_cr_settings->data['custom_response_def_owner'] = $row; + +// Custom response default incident type. +$row = []; +$row['name'] = __('Type'); +$row['control'] = html_print_select( + $integria_types_values, + 'cr_incident_type', + $config['cr_incident_type'], + '', + __('Select'), + 0, + true, + false, + true, + '', + false +); +$table_cr_settings->data['custom_response_incident_type'] = $row; + +// Custom response default incident status. +$row = []; +$row['name'] = __('Status'); +$row['control'] = html_print_select( + $integria_status_values, + 'cr_incident_status', + $config['cr_incident_status'], + '', + __('Select'), + 0, + true, + false, + true, + '', + false +); +$table_cr_settings->data['custom_response_incident_status'] = $row; + +// Test. +$row = []; +$row['name'] = __('Test'); +$row['control'] = html_print_button(__('Start'), 'test-integria', false, '', 'class="sub next"', true); +$row['control'] .= ''; +$row['control'] .= ''; +$row['control'] .= ''; +$row['control'] .= ' '; +$table_remote->data['integria_test'] = $row; + +// Print. +echo '
'; +echo ''; +html_print_image('images/integria_logo.png'); +echo ''; +echo '
'; +echo '
'; +echo __('Integria IMS'); +echo '
'; +echo ''; +echo 'https://integriaims.com'; +echo ''; +echo '
'; + +echo "
"; +html_print_input_hidden('update_config', 1); + +// Form enable. +echo '
'; +html_print_table($table_enable); +echo '
'; + +// Form remote. +echo '
'; +echo '
'; +echo ''.__('Integria API settings').''; + +html_print_table($table_remote); + +echo '
'; +echo '
'; + +if ($has_connection != false) { + // Form alert default settings. + echo '
'; + echo '
'; + echo ''.__('Alert default values').''; + + html_print_table($table_alert_settings); + + echo '
'; + echo '
'; + + // Form custom response default settings. + echo '
'; + echo '
'; + echo ''.__('Event custom response default values').''; + + html_print_table($table_cr_settings); + + echo '
'; + echo '
'; + + echo '
'; + html_print_submit_button(__('Update'), 'update_button', false, 'class="sub upd"'); + echo '
'; +} else { + echo '
'; + html_print_submit_button(__('Update and continue'), 'update_button', false, 'class="sub next"'); + echo '
'; +} + + +echo '
'; + +?> + + diff --git a/pandora_console/godmode/users/configure_profile.php b/pandora_console/godmode/users/configure_profile.php index 418add8aa8..8c69c0e0a9 100644 --- a/pandora_console/godmode/users/configure_profile.php +++ b/pandora_console/godmode/users/configure_profile.php @@ -18,7 +18,7 @@ check_login(); enterprise_hook('open_meta_frame'); -if (! check_acl($config['id_user'], 0, 'PM')) { +if (! check_acl($config['id_user'], 0, 'UM')) { db_pandora_audit( 'ACL Violation', 'Trying to access Profile Management' @@ -320,24 +320,29 @@ if ($id_profile || $new_profile) { $table->data['IM'] = $row; $table->data[] = '
'; + $disable_option = 'javascript: return false;'; + if (check_acl($config['id_user'], 0, 'PM') || users_is_admin()) { + $disable_option = ''; + } + // Users $row = []; $row['name'] = __('Manage users'); - $row['input'] = html_print_checkbox('user_management', 1, $user_management, true); + $row['input'] = html_print_checkbox('user_management', 1, $user_management, true, false, $disable_option); $table->data['UM'] = $row; $table->data[] = '
'; // DB $row = []; $row['name'] = __('Manage database'); - $row['input'] = html_print_checkbox('db_management', 1, $db_management, true); + $row['input'] = html_print_checkbox('db_management', 1, $db_management, true, false, $disable_option); $table->data['DM'] = $row; $table->data[] = '
'; // Pandora $row = []; $row['name'] = __('%s management', get_product_name()); - $row['input'] = html_print_checkbox('pandora_management', 1, $pandora_management, true); + $row['input'] = html_print_checkbox('pandora_management', 1, $pandora_management, true, false, $disable_option); $table->data['PM'] = $row; $table->data[] = '
'; @@ -359,3 +364,18 @@ if ($id_profile || $new_profile) { } enterprise_hook('close_meta_frame'); + +?> + + diff --git a/pandora_console/godmode/users/configure_user.php b/pandora_console/godmode/users/configure_user.php index 07e9942880..602a536f5a 100644 --- a/pandora_console/godmode/users/configure_user.php +++ b/pandora_console/godmode/users/configure_user.php @@ -828,7 +828,7 @@ $values = [ 0 => __('No'), ]; -$table->data[12][0] = __('Home screen').ui_print_help_tip(__('User can customize the home page. By default, will display \'Agent Detail\'. Example: Select \'Other\' and type sec=estado&sec2=operation/agentes/estado_agente to show agent detail view'), true); +$table->data[12][0] = __('Home screen').ui_print_help_tip(__('User can customize the home page. By default, will display \'Agent Detail\'. Example: Select \'Other\' and type index.php?sec=estado&sec2=operation/agentes/ver_agente&id_agente=1 to show agent detail view'), true); $values = [ 'Default' => __('Default'), 'Visual console' => __('Visual console'), diff --git a/pandora_console/godmode/users/profile_list.php b/pandora_console/godmode/users/profile_list.php index da77dffd9f..a87323f0f8 100644 --- a/pandora_console/godmode/users/profile_list.php +++ b/pandora_console/godmode/users/profile_list.php @@ -362,7 +362,10 @@ foreach ($profiles as $profile) { $data['PM'] = ($profile['pandora_management'] ? $img : ''); $table->cellclass[]['operations'] = 'action_buttons'; $data['operations'] = ''.html_print_image('images/config.png', true, ['title' => __('Edit')]).''; - $data['operations'] .= ''.html_print_image('images/cross.png', true).''; + if (check_acl($config['id_user'], 0, 'PM') || users_is_admin()) { + $data['operations'] .= ''.html_print_image('images/cross.png', true).''; + } + array_push($table->data, $data); } diff --git a/pandora_console/godmode/users/user_list.php b/pandora_console/godmode/users/user_list.php index 4e8cfbb2c1..6a02f4bb57 100644 --- a/pandora_console/godmode/users/user_list.php +++ b/pandora_console/godmode/users/user_list.php @@ -420,7 +420,9 @@ else { $u = get_user_info($key); $g = users_get_groups($key, 'AR', $u['is_admin']); $result = array_intersect($g, $own_groups); - if (!$usr['is_admin'] && !empty($result)) { + + // Show users without profile too. + if (!$usr['is_admin'] && !empty($result) || (!$usr['is_admin'] && db_get_all_rows_field_filter('tusuario_perfil', 'id_usuario', $usr['id_user']) === false)) { $info[$key] = $usr; } diff --git a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php index ed7e1f3b10..ed523d0b82 100644 --- a/pandora_console/godmode/wizards/DiscoveryTaskList.class.php +++ b/pandora_console/godmode/wizards/DiscoveryTaskList.class.php @@ -200,7 +200,7 @@ class DiscoveryTaskList extends Wizard { global $config; - if (! check_acl($config['id_user'], 0, 'PM')) { + if (! check_acl($config['id_user'], 0, 'AW')) { db_pandora_audit( 'ACL Violation', 'Trying to access recon task viewer' @@ -241,7 +241,7 @@ class DiscoveryTaskList extends Wizard { global $config; - if (! check_acl($config['id_user'], 0, 'PM')) { + if (!$this->aclMulticheck('RR|RW|RM|PM')) { db_pandora_audit( 'ACL Violation', 'Trying to access recon task viewer' @@ -270,7 +270,7 @@ class DiscoveryTaskList extends Wizard { global $config; - if (! check_acl($config['id_user'], 0, 'PM')) { + if (! check_acl($config['id_user'], 0, 'RM')) { db_pandora_audit( 'ACL Violation', 'Trying to access recon task viewer' @@ -313,13 +313,9 @@ class DiscoveryTaskList extends Wizard check_login(); - if (! check_acl($config['id_user'], 0, 'PM')) { - db_pandora_audit( - 'ACL Violation', - 'Trying to access recon task viewer' - ); - include 'general/noaccess.php'; - return false; + if (!$this->aclMulticheck('AR|AW|AM')) { + // Tasklist are allowed only of agent managers. + return ''; } // Get all discovery servers. @@ -341,7 +337,7 @@ class DiscoveryTaskList extends Wizard // -------------------------------- // FORCE A RECON TASK // -------------------------------- - if (check_acl($config['id_user'], 0, 'PM')) { + if (check_acl($config['id_user'], 0, 'AW')) { if (isset($_GET['force'])) { $id = (int) get_parameter_get('force', 0); servers_force_recon_task($id); @@ -387,8 +383,10 @@ class DiscoveryTaskList extends Wizard // Operations. $table->headstyle[9] .= 'min-width: 150px; width: 150px;'; - $table->head[0] = __('Force'); - $table->align[0] = 'left'; + if (check_acl($config['id_user'], 0, 'AW')) { + $table->head[0] = __('Force'); + $table->align[0] = 'left'; + } $table->head[1] = __('Task name'); $table->align[1] = 'left'; @@ -455,11 +453,13 @@ class DiscoveryTaskList extends Wizard } if ($task['disabled'] == 0 && $server_name !== '') { - $data[0] = ''; - $data[0] .= html_print_image('images/target.png', true, ['title' => __('Force')]); - $data[0] .= ''; + if (check_acl($config['id_user'], 0, 'AW')) { + $data[0] = ''; + $data[0] .= html_print_image('images/target.png', true, ['title' => __('Force')]); + $data[0] .= ''; + } } else if ($task['disabled'] == 2) { $data[0] = ui_print_help_tip( __('This task has not been completely defined, please edit it'), @@ -622,18 +622,20 @@ class DiscoveryTaskList extends Wizard && $task['type'] != DISCOVERY_APP_ORACLE && $task['type'] != DISCOVERY_CLOUD_AWS_RDS ) { - $data[9] .= ''; - $data[9] .= html_print_image( - 'images/dynamic_network_icon.png', - true - ); - $data[9] .= ''; + if (check_acl($config['id_user'], 0, 'MR')) { + $data[9] .= ''; + $data[9] .= html_print_image( + 'images/dynamic_network_icon.png', + true + ); + $data[9] .= ''; + } } if (check_acl( $config['id_user'], $task['id_group'], - 'PM' + 'AW' ) ) { if ($ipam === true) { @@ -733,6 +735,16 @@ class DiscoveryTaskList extends Wizard { if ($script !== false) { switch ($script['type']) { + case DISCOVERY_SCRIPT_APP_VMWARE: + return 'wiz=app&mode=vmware&page=0'; + + case DISCOVERY_SCRIPT_IPAM_RECON: + return ''; + + case DISCOVERY_SCRIPT_IPMI_RECON: + default: + return 'wiz=hd&mode=customnetscan'; + case DISCOVERY_SCRIPT_CLOUD_AWS: switch ($task['type']) { case DISCOVERY_CLOUD_AWS_EC2: @@ -744,16 +756,6 @@ class DiscoveryTaskList extends Wizard default: return 'wiz=cloud'; } - - case DISCOVERY_SCRIPT_APP_VMWARE: - return 'wiz=app&mode=vmware&page=0'; - - case DISCOVERY_SCRIPT_IPAM_RECON: - return ''; - - case DISCOVERY_SCRIPT_IPMI_RECON: - default: - return 'wiz=hd&mode=customnetscan'; } } diff --git a/pandora_console/godmode/wizards/HostDevices.class.php b/pandora_console/godmode/wizards/HostDevices.class.php index fb9fba2cdd..fd7811f2e9 100755 --- a/pandora_console/godmode/wizards/HostDevices.class.php +++ b/pandora_console/godmode/wizards/HostDevices.class.php @@ -87,6 +87,7 @@ class HostDevices extends Wizard ) { $this->setBreadcrum([]); + $this->access = 'AW'; $this->task = []; $this->msg = $msg; $this->icon = $icon; @@ -100,6 +101,32 @@ class HostDevices extends Wizard } + /** + * Checks if environment is ready, + * returns array + * icon: icon to be displayed + * label: label to be displayed + * + * @return array With data. + **/ + public function load() + { + global $config; + // Check access. + check_login(); + + if (! $this->aclMulticheck('AW|PM')) { + return false; + } + + return [ + 'icon' => $this->icon, + 'label' => $this->label, + 'url' => $this->url, + ]; + } + + /** * Run wizard manager. * @@ -116,37 +143,42 @@ class HostDevices extends Wizard if ($mode === null) { $buttons = []; - $buttons[] = [ - 'url' => $this->url.'&mode=netscan', - 'icon' => 'images/wizard/netscan.png', - 'label' => __('Net Scan'), - ]; - if (enterprise_installed()) { + if (check_acl($config['id_user'], 0, $this->access)) { $buttons[] = [ - 'url' => $this->url.'&mode=importcsv', - 'icon' => ENTERPRISE_DIR.'/images/wizard/csv.png', - 'label' => __('Import CSV'), + 'url' => $this->url.'&mode=netscan', + 'icon' => 'images/wizard/netscan.png', + 'label' => __('Net Scan'), ]; + if (enterprise_installed()) { + $buttons[] = [ + 'url' => $this->url.'&mode=importcsv', + 'icon' => ENTERPRISE_DIR.'/images/wizard/csv.png', + 'label' => __('Import CSV'), + ]; + + $buttons[] = [ + 'url' => $this->url.'&mode=deploy', + 'icon' => ENTERPRISE_DIR.'/images/wizard/deployment.png', + 'label' => __('Agent deployment'), + ]; + } + $buttons[] = [ - 'url' => $this->url.'&mode=deploy', - 'icon' => ENTERPRISE_DIR.'/images/wizard/deployment.png', - 'label' => __('Agent deployment'), + 'url' => $this->url.'&mode=customnetscan', + 'icon' => '/images/wizard/customnetscan.png', + 'label' => __('Custom NetScan'), ]; } - $buttons[] = [ - 'url' => $this->url.'&mode=customnetscan', - 'icon' => '/images/wizard/customnetscan.png', - 'label' => __('Custom NetScan'), - ]; - - $buttons[] = [ - 'url' => $this->url.'&mode=managenetscanscripts', - 'icon' => '/images/wizard/managenetscanscripts.png', - 'label' => __('Manage NetScan scripts'), - ]; + if (check_acl($config['id_user'], 0, 'PM')) { + $buttons[] = [ + 'url' => $this->url.'&mode=managenetscanscripts', + 'icon' => '/images/wizard/managenetscanscripts.png', + 'label' => __('Manage NetScan scripts'), + ]; + } $this->prepareBreadcrum( [ @@ -311,11 +343,11 @@ class HostDevices extends Wizard ) { // Default values, no data received. // User is accesing directly to this page. - if (users_is_admin() !== true && check_acl( + if (check_acl( $config['id_usuario'], $this->task['id_group'], - 'PM' - ) !== true + $this->access + ) != true ) { $this->msg = __('You have no access to edit this task.'); return false; @@ -487,7 +519,7 @@ class HostDevices extends Wizard check_login(); - if (! check_acl($config['id_user'], 0, 'PM')) { + if (! check_acl($config['id_user'], 0, $this->access)) { db_pandora_audit( 'ACL Violation', 'Trying to access Agent Management' @@ -529,11 +561,11 @@ class HostDevices extends Wizard // Check ACL. If user is not able to manage target task, // redirect him to main page. - if (users_is_admin() !== true && check_acl( + if (check_acl( $config['id_usuario'], $this->task['id_group'], - 'PM' - ) !== true + $this->access + ) != true ) { $form['form']['action'] = $this->url.'&mode=netscan&page='.($this->page - 1); } @@ -750,7 +782,7 @@ class HostDevices extends Wizard [ 'name' => 'id_group', 'returnAllGroup' => false, - 'privilege' => 'PM', + 'privilege' => $this->access, 'type' => 'select_groups', 'selected' => $this->task['id_group'], 'return' => true, diff --git a/pandora_console/godmode/wizards/Wizard.main.php b/pandora_console/godmode/wizards/Wizard.main.php index 3a65560285..cb29d78c06 100644 --- a/pandora_console/godmode/wizards/Wizard.main.php +++ b/pandora_console/godmode/wizards/Wizard.main.php @@ -87,6 +87,13 @@ class Wizard */ public $msg; + /** + * Defines access level to use this util. + * + * @var string + */ + public $access = 'AR'; + /** * Setter for breadcrum @@ -234,6 +241,42 @@ class Wizard public function run() { ui_require_css_file('wizard'); + // Check access. + check_login(); + + if (! $this->aclMulticheck()) { + return; + } + } + + + /** + * Check multiple acl perms. + * + * @param string $access Access in PM|AR|RR format. Optional. + * + * @return boolean Alowed or not. + */ + public function aclMulticheck($access=null) + { + global $config; + + if (isset($access)) { + $perms = explode('|', $access); + } else { + $perms = explode('|', $this->access); + } + + $allowed = false; + foreach ($perms as $perm) { + $allowed = $allowed || (bool) check_acl( + $config['id_user'], + 0, + $perm + ); + } + + return $allowed; } @@ -247,6 +290,14 @@ class Wizard **/ public function load() { + global $config; + // Check access. + check_login(); + + if (! $this->aclMulticheck()) { + return false; + } + return [ 'icon' => $this->icon, 'label' => $this->label, diff --git a/pandora_console/images/console/background/fondo-keep-alive.jpg b/pandora_console/images/console/background/fondo-keep-alive.jpg new file mode 100644 index 0000000000..fbb5b90a5c Binary files /dev/null and b/pandora_console/images/console/background/fondo-keep-alive.jpg differ diff --git a/pandora_console/images/console/icons/status.png b/pandora_console/images/console/icons/status.png new file mode 100644 index 0000000000..6fba320b6f Binary files /dev/null and b/pandora_console/images/console/icons/status.png differ diff --git a/pandora_console/images/console/icons/status_bad.png b/pandora_console/images/console/icons/status_bad.png new file mode 100644 index 0000000000..a6935a5a19 Binary files /dev/null and b/pandora_console/images/console/icons/status_bad.png differ diff --git a/pandora_console/images/console/icons/status_ok.png b/pandora_console/images/console/icons/status_ok.png new file mode 100644 index 0000000000..a23d4dad2e Binary files /dev/null and b/pandora_console/images/console/icons/status_ok.png differ diff --git a/pandora_console/images/console/icons/status_warning.png b/pandora_console/images/console/icons/status_warning.png new file mode 100644 index 0000000000..387de1c755 Binary files /dev/null and b/pandora_console/images/console/icons/status_warning.png differ diff --git a/pandora_console/images/integria.png b/pandora_console/images/integria.png new file mode 100644 index 0000000000..9dcad27e3b Binary files /dev/null and b/pandora_console/images/integria.png differ diff --git a/pandora_console/images/integria_logo.png b/pandora_console/images/integria_logo.png new file mode 100644 index 0000000000..f56ecfdab5 Binary files /dev/null and b/pandora_console/images/integria_logo.png differ diff --git a/pandora_console/images/integria_logo_gray.png b/pandora_console/images/integria_logo_gray.png new file mode 100644 index 0000000000..d901e72493 Binary files /dev/null and b/pandora_console/images/integria_logo_gray.png differ diff --git a/pandora_console/include/ajax/integria_incidents.ajax.php b/pandora_console/include/ajax/integria_incidents.ajax.php new file mode 100644 index 0000000000..3991ecf51c --- /dev/null +++ b/pandora_console/include/ajax/integria_incidents.ajax.php @@ -0,0 +1,60 @@ + 'api_password'])); +$apiPassword = io_output_password( + db_get_value_filter( + 'value', + 'tconfig', + ['token' => 'api_password'] + ) +); $correctLogin = false; $no_login_msg = ''; -// Clean unwanted output +// Clean unwanted output. ob_clean(); // READ THIS: // Special call without checks to retrieve version and build of the Pandora FMS // This info is avalable from the web console without login -// Don't change the format, it is parsed by applications -switch ($info) { - case 'version': - if (!$config['MR']) { - $config['MR'] = 0; - } - - echo 'Pandora FMS '.$pandora_version.' - '.$build_version.' MR'.$config['MR']; +// Don't change the format, it is parsed by applications. +if ($info == 'version') { + if (!$config['MR']) { + $config['MR'] = 0; + } + echo 'Pandora FMS '.$pandora_version.' - '.$build_version.' MR'.$config['MR']; exit; } @@ -68,14 +89,19 @@ if (isInACL($ipOrigin)) { if (empty($apiPassword) || (!empty($apiPassword) && $api_password === $apiPassword)) { $user_in_db = process_user_login($user, $password, true); if ($user_in_db !== false) { + $config['id_usuario'] = $user_in_db; + // Compat. $config['id_user'] = $user_in_db; $correctLogin = true; if (session_status() === PHP_SESSION_NONE) { session_start(); + $_SESSION = []; } $_SESSION['id_usuario'] = $user; + + config_prepare_session(); session_write_close(); } else { $no_login_msg = 'Incorrect user credentials'; @@ -84,7 +110,7 @@ if (isInACL($ipOrigin)) { $no_login_msg = 'Incorrect given API password'; } } else { - $no_login_msg = "IP $ipOrigin is not in ACL list"; + $no_login_msg = 'IP '.$ipOrigin.' is not in ACL list'; } if ($correctLogin) { @@ -93,11 +119,14 @@ if ($correctLogin) { } else { $function_name = ''; - // Check if is an extension function and get the function name + // Check if is an extension function and get the function name. if ($op2 == 'extension') { - $extension_api_url = $config['homedir'].'/'.EXTENSIONS_DIR."/$ext_name/$ext_name.api.php"; - // The extension API file must exist and the extension must be enabled - if (file_exists($extension_api_url) && !in_array($ext_name, extensions_get_disabled_extensions())) { + $extension_api_url = $config['homedir'].'/'.EXTENSIONS_DIR.'/'.$ext_name.'/'.$ext_name.'.api.php'; + // The extension API file must exist and the extension must be + // enabled. + if (file_exists($extension_api_url) + && !in_array($ext_name, extensions_get_disabled_extensions()) + ) { include_once $extension_api_url; $function_name = 'apiextension_'.$op.'_'.$ext_function; } @@ -107,16 +136,19 @@ if ($correctLogin) { if ($op == 'set' && $id) { switch ($op2) { case 'update_agent': - case 'add_module_in_conf': case 'update_module_in_conf': case 'delete_module_in_conf': - - $id_os = db_get_value_sql('select id_os from tagente where id_agente = '.$id); - - if ($id_os == 100) { - returnError('not_allowed_operation_cluster', $returnType); - return false; + $agent = agents_locate_agent($id); + if ($agent !== false) { + $id_os = $agent['id_os']; + if ($id_os == 100) { + returnError( + 'not_allowed_operation_cluster', + $returnType + ); + return false; + } } break; @@ -127,12 +159,16 @@ if ($correctLogin) { case 'create_snmp_module': case 'delete_module': case 'delete_agent': - - $id_os = db_get_value_sql('select id_os from tagente where nombre = "'.$id.'"'); - - if ($id_os == 100) { - returnError('not_allowed_operation_cluster', $returnType); - return false; + $agent = agents_locate_agent($id); + if ($agent !== false) { + $id_os = $agent['id_os']; + if ($id_os == 100) { + returnError( + 'not_allowed_operation_cluster', + $returnType + ); + return false; + } } break; @@ -141,60 +177,98 @@ if ($correctLogin) { case 'update_data_module': case 'update_snmp_module': - $id_os = db_get_value_sql('select id_os from tagente where id_agente = (select id_agente from tagente_modulo where id_agente_modulo ='.$id.')'); + $id_os = db_get_value_sql( + sprintf( + 'SELECT id_os + FROM tagente + WHERE id_agente = ( + SELECT id_agente + FROM tagente_modulo + WHERE id_agente_modulo = %d + )', + $id + ) + ); + if ($id_os == 100) { - returnError('not_allowed_operation_cluster', $returnType); + returnError( + 'not_allowed_operation_cluster', + $returnType + ); return false; } break; case 'delete_user_permission': - if ($user_db === '') { - returnError(__('User or group not specified'), __('User, group not specified')); + returnError( + __('User or group not specified'), + __('User, group not specified') + ); return; } - $id_os = api_set_delete_user_profiles($thrash1, $thrash2, $other, $returnType); + $id_os = api_set_delete_user_profiles( + $thrash1, + $thrash2, + $other, + $returnType + ); if ($id_os != 100) { return; } if ($id_os == false) { - returnError('not_allowed_operation_cluster', $returnType); + returnError( + 'not_allowed_operation_cluster', + $returnType + ); return false; } break; case 'add_permission_user_to_group': - - if ($user_db == null || $group_db == null || $id_up == null) { - returnError(__('User, group or profile not specified'), __('User, group or profile status not specified')); + if ($user_db == null + || $group_db == null + || $id_up == null + ) { + returnError( + __('User, group or profile not specified'), + __('User, group or profile status not specified') + ); return; } - $id_os = api_set_add_permission_user_to_group($thrash1, $thrash2, $other, $returnType); + $id_os = api_set_add_permission_user_to_group( + $thrash1, + $thrash2, + $other, + $returnType + ); if ($id_os != 100) { return; } if ($id_os == false) { - returnError('not_allowed_operation_cluster', $returnType); + returnError( + 'not_allowed_operation_cluster', + $returnType + ); return false; } break; default: - - // break; + // Ignore. + break; } } } - // Check if the function exists + // Check if the function exists. if (function_exists($function_name)) { if (!DEBUG) { error_reporting(0); @@ -205,18 +279,37 @@ if ($correctLogin) { ini_set('display_errors', 1); } - call_user_func($function_name, $id, $id2, $other, $returnType, $user_in_db); + call_user_func( + $function_name, + $id, + $id2, + $other, + $returnType, + $user_in_db + ); } else { returnError('no_exist_operation', $returnType); } } } else { - // TODO: Implement a new switch in config to enable / disable - // ACL auth failure: if enabled and have lots of traffic can produce millions - // of records and a considerable OVERHEAD in the system :( - // db_pandora_audit("API access Failed", $no_login_msg, $user, $ipOrigin); + /* + * //TODO: Implement a new switch in config to enable / disable + * ACL auth failure: if enabled and have lots of traffic can produce + * millions of records and a considerable OVERHEAD in the system :( + * db_pandora_audit("API access Failed", $no_login_msg, $user, $ipOrigin); + */ + sleep(15); - // Protection on DoS attacks + // Protection on DoS attacks. echo 'auth error'; } + +// Logout. +if (session_status() === PHP_SESSION_ACTIVE) { + $_SESSION = []; + // Could give a warning if no session file is created. Ignore. + @session_destroy(); + header_remove('Set-Cookie'); + setcookie(session_name(), $_COOKIE[session_name()], (time() - 4800), '/'); +} diff --git a/pandora_console/include/chart_generator.php b/pandora_console/include/chart_generator.php index 2ae768d4fe..0d1d138ae6 100644 --- a/pandora_console/include/chart_generator.php +++ b/pandora_console/include/chart_generator.php @@ -1,22 +1,39 @@ + + $_REQUEST['session_id']]); +if (check_login(false) === false) { + // Error handler. + ?> + + + + + Access denied + + + + + + + + +

Access is not granted

+ + + + + '; - echo ''; - ui_print_error_message(__('There was a problem connecting with the node')); - echo ''; - echo ''; + ?> + + + + + + load_tables(); } @@ -85,16 +161,18 @@ if (file_exists('languages/'.$user_language.'.mo')) { '; switch ($type_graph_pdf) { @@ -208,25 +286,12 @@ if (file_exists('languages/'.$user_language.'.mo')) { break; default: - // code... + // Code... break; } echo '
'; - + echoPhantomCallback(); ?> - - - diff --git a/pandora_console/include/class/ConsoleSupervisor.php b/pandora_console/include/class/ConsoleSupervisor.php index 87a6f2dca0..013a7e967f 100644 --- a/pandora_console/include/class/ConsoleSupervisor.php +++ b/pandora_console/include/class/ConsoleSupervisor.php @@ -209,6 +209,12 @@ class ConsoleSupervisor $this->getUMMessages(); + /* + * Check if the Server and Console has + * the same versions. + */ + $this->checkConsoleServerVersions(); + } @@ -435,6 +441,12 @@ class ConsoleSupervisor $this->getUMMessages(); + /* + * Check if the Server and Console has + * the same versions. + */ + $this->checkConsoleServerVersions(); + } @@ -873,18 +885,20 @@ class ConsoleSupervisor { global $config; + $remote_config_dir = io_safe_output($config['remote_config']); + if (enterprise_installed() && isset($config['license_nms']) && $config['license_nms'] != 1 ) { - if (is_readable($config['remote_config']) !== true) { + if (is_readable($remote_config_dir) !== true) { $this->notify( [ 'type' => 'NOTIF.PERMISSIONS.REMOTE_CONFIG', 'title' => __('Remote configuration directory is not readable'), 'message' => __( 'Remote configuration directory %s is not readable. Please, adjust configuration.', - $config['remote_config'] + $remote_config_dir ), 'url' => ui_get_full_url('index.php?sec=general&sec2=godmode/setup/setup§ion=general'), ] @@ -896,14 +910,14 @@ class ConsoleSupervisor ); } - if (is_writable($config['remote_config'].'/conf') !== true) { + if (is_writable($remote_config_dir.'/conf') !== true) { $this->notify( [ 'type' => 'NOTIF.PERMISSIONS.REMOTE_CONFIG.CONF', 'title' => __('Remote configuration directory is not writable'), 'message' => __( 'Remote configuration directory %s is not writable. Please, adjust configuration.', - $config['remote_config'].'/conf' + $remote_config_dir.'/conf' ), 'url' => ui_get_full_url('index.php?sec=general&sec2=godmode/setup/setup§ion=general'), ] @@ -914,14 +928,14 @@ class ConsoleSupervisor ); } - if (is_writable($config['remote_config'].'/collections') !== true) { + if (is_writable($remote_config_dir.'/collections') !== true) { $this->notify( [ 'type' => 'NOTIF.PERMISSIONS.REMOTE_CONFIG.COLLECTIONS', 'title' => __('Remote collections directory is not writable'), 'message' => __( 'Collections directory %s is not writable. Please, adjust configuration.', - $config['remote_config'].'/collections' + $remote_config_dir.'/collections' ), 'url' => ui_get_full_url('index.php?sec=general&sec2=godmode/setup/setup§ion=general'), ] @@ -932,14 +946,14 @@ class ConsoleSupervisor ); } - if (is_writable($config['remote_config'].'/md5') !== true) { + if (is_writable($remote_config_dir.'/md5') !== true) { $this->notify( [ 'type' => 'NOTIF.PERMISSIONS.REMOTE_CONFIG.MD5', 'title' => __('Remote md5 directory is not writable'), 'message' => __( 'MD5 directory %s is not writable. Please, adjust configuration.', - $config['remote_config'].'/md5' + $remote_config_dir.'/md5' ), 'url' => ui_get_full_url('index.php?sec=general&sec2=godmode/setup/setup§ion=general'), ] @@ -957,7 +971,7 @@ class ConsoleSupervisor $MAX_BADXML_FILES_DATA_IN = 150; $filecount = $this->countFiles( - $config['remote_config'], + $remote_config_dir, '', $MAX_FILES_DATA_IN ); @@ -970,7 +984,7 @@ class ConsoleSupervisor 'message' => __( 'There are more than %d files in %s. Consider checking DataServer performance', $MAX_FILES_DATA_IN, - $config['remote_config'] + $remote_config_dir ), 'url' => ui_get_full_url('index.php?sec=general&sec2=godmode/setup/setup§ion=perf'), ] @@ -980,7 +994,7 @@ class ConsoleSupervisor } $filecount = $this->countFiles( - $config['remote_config'], + $remote_config_dir, '/^.*BADXML$/', $MAX_BADXML_FILES_DATA_IN ); @@ -993,7 +1007,7 @@ class ConsoleSupervisor 'message' => __( 'There are more than %d files in %s. Consider checking software agents.', $MAX_BADXML_FILES_DATA_IN, - $config['remote_config'] + $remote_config_dir ), 'url' => ui_get_full_url('index.php?sec=general&sec2=godmode/setup/setup§ion=perf'), ] @@ -1266,7 +1280,8 @@ class ConsoleSupervisor $PHPSerialize_precision = ini_get('serialize_precision'); // PhantomJS status. - $result_ejecution = exec($config['phantomjs_bin'].'/phantomjs --version'); + $phantomjs_dir = io_safe_output($config['phantomjs_bin']); + $result_ejecution = exec($phantomjs_dir.'/phantomjs --version'); // PHP version checks. $php_version = phpversion(); @@ -1451,8 +1466,9 @@ class ConsoleSupervisor 'type' => 'NOTIF.PHP.SERIALIZE_PRECISION', 'title' => sprintf( __("Not recommended '%s' value in PHP configuration"), - 'serialze_precision' - ), 'message' => sprintf( + 'serialize_precision' + ), + 'message' => sprintf( __('Recommended value is: %s'), sprintf('-1') ).'

'.__('Please, change it on your PHP configuration file (php.ini) or contact with administrator'), @@ -2061,8 +2077,10 @@ class ConsoleSupervisor { global $config; - if (($config['fontpath'] == '') - || (file_exists($config['fontpath']) === false) + $fontpath = io_safe_output($config['fontpath']); + + if (($fontpath == '') + || (file_exists($fontpath) === false) ) { $this->notify( [ @@ -2328,4 +2346,35 @@ class ConsoleSupervisor } + /** + * Check if all servers and console versions are the same + * + * @return void + */ + public function checkConsoleServerVersions() + { + global $config; + // List all servers except satellite server + $server_version_list = db_get_all_rows_sql( + 'SELECT name, version FROM tserver WHERE server_type != '.SERVER_TYPE_ENTERPRISE_SATELLITE + ); + + foreach ($server_version_list as $server) { + if (strpos($server['version'], $config['current_package_enterprise']) === false) { + $title_ver_misaligned = $server['name'].' version misaligned with Console'; + $message_ver_misaligned = 'Server '.$server['name'].' and this console have different versions. This might cause several malfunctions. Please, update this server.'; + + $this->notify( + [ + 'type' => 'NOTIF.SERVER.MISALIGNED', + 'title' => __($title_ver_misaligned), + 'message' => __($message_ver_misaligned), + 'url' => ui_get_full_url('index.php?sec=messages&sec2=godmode/update_manager/update_manager&tab=online'), + ] + ); + } + } + } + + } diff --git a/pandora_console/include/class/CredentialStore.class.php b/pandora_console/include/class/CredentialStore.class.php new file mode 100644 index 0000000000..188950d92a --- /dev/null +++ b/pandora_console/include/class/CredentialStore.class.php @@ -0,0 +1,1203 @@ +AJAXMethods); + } + + + /** + * Generates a JSON error. + * + * @param string $msg Error message. + * + * @return void + */ + public function error($msg) + { + echo json_encode( + ['error' => $msg] + ); + } + + + /** + * Minor function to dump json message as ajax response. + * + * @param string $type Type: result || error. + * @param string $msg Message. + * @param boolean $delete Deletion messages. + * + * @return void + */ + private function ajaxMsg($type, $msg, $delete=false) + { + $msg_err = 'Failed while saving: %s'; + $msg_ok = 'Successfully saved into keystore '; + + if ($delete) { + $msg_err = 'Failed while removing: %s'; + $msg_ok = 'Successfully deleted '; + } + + if ($type == 'error') { + echo json_encode( + [ + $type => ui_print_error_message( + __( + $msg_err, + $msg + ), + '', + true + ), + ] + ); + } else { + echo json_encode( + [ + $type => ui_print_success_message( + __( + $msg_ok, + $msg + ), + '', + true + ), + ] + ); + } + + exit; + } + + + /** + * Initializes object and validates user access. + * + * @param string $ajax_controller Path of ajaxController, is the 'page' + * variable sent in ajax calls. + * + * @return Object + */ + public function __construct($ajax_controller) + { + global $config; + + // Check access. + check_login(); + + if (! check_acl($config['id_user'], 0, 'AR')) { + db_pandora_audit( + 'ACL Violation', + 'Trying to access event viewer' + ); + + if (is_ajax()) { + echo json_encode(['error' => 'noaccess']); + } + + include 'general/noaccess.php'; + exit; + } + + $this->ajaxController = $ajax_controller; + + return $this; + } + + + /** + * Returns an array with all the credentials matching filter and ACL. + * + * @param array $fields Fields array or 'count' keyword to retrieve count. + * @param array $filter Filters to be applied. + * @param integer $offset Offset (pagination). + * @param integer $limit Limit (pagination). + * @param string $order Sort order. + * @param string $sort_field Sort field. + * + * @return array With all results or false if error. + * @throws Exception On error. + */ + public static function getAll( + $fields, + $filter, + $offset=null, + $limit=null, + $order=null, + $sort_field=null + ) { + $sql_filters = []; + $order_by = ''; + $pagination = ''; + + global $config; + + if (!is_array($filter)) { + error_log('[credential_get_all] Filter must be an array.'); + throw new Exception('[credential_get_all] Filter must be an array.'); + } + + $count = false; + if (!is_array($fields) && $fields == 'count') { + $fields = ['cs.*']; + $count = true; + } else if (!is_array($fields)) { + error_log('[credential_get_all] Fields must be an array or "count".'); + throw new Exception('[credential_get_all] Fields must be an array or "count".'); + } + + if (isset($filter['product']) && !empty($filter['product'])) { + $sql_filters[] = sprintf(' AND cs.product = "%s"', $filter['product']); + } + + if (isset($filter['free_search']) && !empty($filter['free_search'])) { + $sql_filters[] = vsprintf( + ' AND (lower(cs.username) like lower("%%%s%%") + OR cs.identifier like "%%%s%%" + OR lower(cs.product) like lower("%%%s%%"))', + array_fill(0, 3, $filter['free_search']) + ); + } + + if (isset($filter['filter_id_group']) && $filter['filter_id_group'] > 0) { + $propagate = db_get_value( + 'propagate', + 'tgrupo', + 'id_grupo', + $filter['filter_id_group'] + ); + + if (!$propagate) { + $sql_filters[] = sprintf( + ' AND cs.id_group = %d ', + $filter['filter_id_group'] + ); + } else { + $groups = [ $filter['filter_id_group'] ]; + $childrens = groups_get_childrens($id_group, null, true); + if (!empty($childrens)) { + foreach ($childrens as $child) { + $groups[] = (int) $child['id_grupo']; + } + } + + $filter['filter_id_group'] = $groups; + $sql_filters[] = sprintf( + ' AND cs.id_group IN (%s) ', + join(',', $filter['filter_id_group']) + ); + } + } + + if (isset($filter['group_list']) && is_array($filter['group_list'])) { + $sql_filters[] = sprintf( + ' AND cs.id_group IN (%s) ', + join(',', $filter['group_list']) + ); + } else if (users_is_admin() !== true) { + $user_groups = users_get_groups( + $config['id_user'], + 'AR' + ); + + // Always add group 'ALL' because 'ALL' group credentials + // must be available for all users. + if (is_array($user_groups) === true) { + $user_groups = ([0] + array_keys($user_groups)); + } else { + $user_groups = [0]; + } + + $sql_filters[] = sprintf( + ' AND cs.id_group IN (%s) ', + join(',', $user_groups) + ); + } + + if (isset($filter['identifier'])) { + $sql_filters[] = sprintf( + ' AND cs.identifier = "%s" ', + $filter['identifier'] + ); + } + + if (isset($order)) { + $dir = 'asc'; + if ($order == 'desc') { + $dir = 'desc'; + }; + + if (in_array( + $sort_field, + [ + 'group', + 'identifier', + 'product', + 'username', + 'options', + ] + ) + ) { + $order_by = sprintf( + 'ORDER BY `%s` %s', + $sort_field, + $dir + ); + } + } + + if (isset($limit) && $limit > 0 + && isset($offset) && $offset >= 0 + ) { + $pagination = sprintf( + ' LIMIT %d OFFSET %d ', + $limit, + $offset + ); + } + + $sql = sprintf( + 'SELECT %s + FROM tcredential_store cs + LEFT JOIN tgrupo tg + ON tg.id_grupo = cs.id_group + WHERE 1=1 + %s + %s + %s', + join(',', $fields), + join(' ', $sql_filters), + $order_by, + $pagination + ); + + if ($count) { + $sql = sprintf('SELECT count(*) as n FROM ( %s ) tt', $sql); + + return db_get_value_sql($sql); + } + + return db_get_all_rows_sql($sql); + } + + + /** + * Retrieves target key from keystore or false in case of error. + * + * @param string $identifier Key identifier. + * + * @return array Key or false if error. + */ + public static function getKey($identifier) + { + global $config; + + if (empty($identifier)) { + return false; + } + + $keys = self::getAll( + [ + 'cs.*', + 'tg.nombre as `group`', + ], + ['identifier' => $identifier] + ); + + if (is_array($keys) === true) { + // Only 1 must exist. + $key = $keys[0]; + + // Decrypt content. + $key['username'] = io_output_password($key['username']); + $key['password'] = io_output_password($key['password']); + + return $key; + } + + return false; + } + + + /** + * Return all keys avaliable for current user. + * + * @param string $product Filter by product. + * + * @return array Keys or false if error. + */ + public static function getKeys($product=false) + { + global $config; + + if ($product !== false) { + $filter['product'] = $product; + } + + $keys = self::getAll( + [ + 'cs.*', + 'tg.nombre as `group`', + ], + $filter + ); + + if (is_array($keys) === true) { + // Improve usage and decode output. + $return = array_reduce( + $keys, + function ($carry, $item) { + $item['username'] = io_output_password($item['username']); + $item['password'] = io_output_password($item['password']); + $carry[$item['identifier']] = $item['identifier']; + return $carry; + } + ); + + return $return; + } + + return false; + } + + + /** + * Ajax method invoked by datatables to draw content. + * + * @return void + */ + public function draw() + { + // Datatables offset, limit and order. + $filter = get_parameter('filter', []); + $start = get_parameter('start', 0); + $length = get_parameter('length', $config['block_size']); + $order = get_datatable_order(true); + try { + ob_start(); + + $fields = [ + 'cs.*', + 'tg.nombre as `group`', + ]; + + // Retrieve data. + $data = $this->getAll( + // Fields. + $fields, + // Filter. + $filter, + // Offset. + $start, + // Limit. + $length, + // Order. + $order['direction'], + // Sort field. + $order['field'] + ); + + // Retrieve counter. + $count = $this->getAll( + 'count', + $filter + ); + + if ($data) { + $data = array_reduce( + $data, + function ($carry, $item) { + // Transforms array of arrays $data into an array + // of objects, making a post-process of certain fields. + $tmp = (object) $item; + $tmp->username = io_output_password($tmp->username); + + if (empty($tmp->group)) { + $tmp->group = __('All'); + } else { + $tmp->group = io_safe_output($tmp->group); + } + + $carry[] = $tmp; + return $carry; + } + ); + } + + // Datatables format: RecordsTotal && recordsfiltered. + echo json_encode( + [ + 'data' => $data, + 'recordsTotal' => $count, + 'recordsFiltered' => $count, + ] + ); + // Capture output. + $response = ob_get_clean(); + } catch (Exception $e) { + echo json_encode(['error' => $e->getMessage()]); + exit; + } + + // If not valid, show error with issue. + json_decode($response); + if (json_last_error() == JSON_ERROR_NONE) { + // If valid dump. + echo $response; + } else { + echo json_encode( + ['error' => $response] + ); + } + + exit; + } + + + /** + * Prints inputs for modal "Add key". + * + * @return void + */ + public function loadModal() + { + $identifier = get_parameter('identifier', null); + $key = self::getKey($identifier); + + echo $this->printInputs($key); + } + + + /** + * Prepare variables received using form. AJAX environment only. + * + * @return array of values processed or false in case of error. + */ + private function prepareKeyValues() + { + $identifier = get_parameter('identifier', null); + $id_group = get_parameter('id_group', null); + $product = get_parameter('product', null); + $username = get_parameter('username', null); + $password = get_parameter('password', null); + $extra_1 = get_parameter('extra_1', null); + $extra_2 = get_parameter('extra_2', null); + + if (empty($identifier)) { + $error = __('Key identifier is required'); + } else if ($id_group === null) { + $error = __('You must select a group where store this key!'); + } else if (empty($product)) { + $error = __('You must specify a product type'); + } else if (empty($username) && (empty($password))) { + $error = __('You must specify a username and/or password'); + } + + // Encrypt content (if needed). + $values = [ + 'identifier' => $identifier, + 'id_group' => $id_group, + 'product' => $product, + 'username' => io_input_password($username), + 'password' => io_input_password($password), + 'extra_1' => $extra_1, + 'extra_2' => $extra_2, + ]; + + // Spaces are not allowed. + $values['identifier'] = preg_replace('/\s+/', '-', trim($identifier)); + + return $values; + } + + + /** + * Stores a key into credential store. + * + * @param array $values Key definition. + * @param string $identifier Update or create. + * + * @return boolean True if ok, false if not ok. + */ + private function storeKey($values, $identifier=false) + { + if ($identifier === false) { + // New. + return db_process_sql_insert('tcredential_store', $values); + } else { + // Update. + return db_process_sql_update( + 'tcredential_store', + $values, + ['identifier' => $identifier] + ); + } + + } + + + /** + * Add a new key into Credential Store + * + * @return void + */ + public function addKey() + { + global $config; + + $values = $this->prepareKeyValues(); + + if ($this->storeKey($values) === false) { + $this->ajaxMsg('error', $config['dbconnection']->error); + } else { + $this->ajaxMsg('result', $values['identifier']); + } + + exit; + } + + + /** + * Add a new key into Credential Store + * + * @return void + */ + public function updateKey() + { + global $config; + + $values = $this->prepareKeyValues(); + $identifier = $values['identifier']; + + if ($this->storeKey($values, $identifier) === false) { + $this->ajaxMsg('error', $config['dbconnection']->error); + } else { + $this->ajaxMsg('result', $identifier); + } + + exit; + } + + + /** + * AJAX method. Delete key from keystore. + * + * @return void + */ + public function deleteKey() + { + global $config; + + $identifier = get_parameter('identifier', null); + + if (empty($identifier)) { + $this->ajaxMsg('error', __('identifier cannot be empty'), true); + } + + if (self::getKey($identifier) === false) { + // User has no grants to delete target key. + $this->ajaxMsg('error', __('Not allowed'), true); + } + + if (db_process_sql_delete( + 'tcredential_store', + ['identifier' => $identifier] + ) === false + ) { + $this->ajaxMsg('error', $config['dbconnection']->error, true); + } else { + $this->ajaxMsg('result', $identifier, true); + } + + } + + + /** + * Run CredentialStore (main page). + * + * @return void + */ + public function run() + { + global $config; + + // Require specific CSS and JS. + ui_require_css_file('wizard'); + ui_require_css_file('discovery'); + ui_require_css_file('credential_store'); + + if (!isset($config['encryption_passphrase'])) { + $url = 'https://pandorafms.com/docs/index.php?title=Pandora:Documentation_en:Password_Encryption'; + if ($config['language'] == 'es') { + $url = 'https://pandorafms.com/docs/index.php?title=Pandora:Documentation_es:Cifrado_Contrase%C3%B1as'; + } + + ui_print_warning_message( + __( + 'Database encryption is not enabled. Credentials will be stored in plaintext. %s', + ''.__('How to configure encryption.').'' + ) + ); + } + + // Datatables list. + try { + $columns = [ + 'group', + 'identifier', + 'product', + 'username', + 'options', + ]; + + $column_names = [ + __('Group'), + __('Identifier'), + __('Product'), + __('User'), + [ + 'text' => __('Options'), + 'class' => 'action_buttons', + ], + ]; + + $this->tableId = 'keystore'; + // Load datatables user interface. + ui_print_datatable( + [ + 'id' => $this->tableId, + 'class' => 'info_table', + 'style' => 'width: 100%', + 'columns' => $columns, + 'column_names' => $column_names, + 'ajax_url' => $this->ajaxController, + 'ajax_data' => ['method' => 'draw'], + 'ajax_postprocess' => 'process_datatables_item(item)', + 'no_sortable_columns' => [-1], + 'order' => [ + 'field' => 'identifier', + 'direction' => 'asc', + ], + 'search_button_class' => 'sub filter float-right', + 'form' => [ + 'inputs' => [ + [ + 'label' => __('Group'), + 'type' => 'select', + 'id' => 'filter_id_group', + 'name' => 'filter_id_group', + 'options' => users_get_groups_for_select( + $config['id_user'], + 'AR', + true, + true, + false + ), + ], + [ + 'label' => __('Free search'), + 'type' => 'text', + 'class' => 'mw250px', + 'id' => 'free_search', + 'name' => 'free_search', + ], + ], + ], + ] + ); + } catch (Exception $e) { + echo $e->getMessage(); + } + + // Auxiliar div. + $modal = ''; + $msg = ''; + $aux = ''; + + echo $modal.$msg.$aux; + + // Create button. + echo '
'; + html_print_submit_button( + __('Add key'), + 'create', + false, + 'class="sub next"' + ); + echo '
'; + + echo $this->loadJS(); + + } + + + /** + * Generates inputs for new/update forms. + * + * @param array $values Values or null. + * + * @return string Inputs. + */ + public function printInputs($values=null) + { + if (!is_array($values)) { + $values = []; + } + + $form = [ + 'action' => '#', + 'id' => 'modal_form', + 'onsubmit' => 'return false;', + 'class' => 'modal', + 'extra' => 'autocomplete="new-password"', + ]; + + $inputs = []; + + $inputs[] = [ + 'label' => __('Identifier'), + 'id' => 'div-identifier', + 'arguments' => [ + 'name' => 'identifier', + 'type' => 'text', + 'value' => $values['identifier'], + 'disabled' => (bool) $values['identifier'], + 'return' => true, + ], + ]; + + $inputs[] = [ + 'label' => __('Group'), + 'arguments' => [ + 'name' => 'id_group', + 'id' => 'id_group', + 'input_class' => 'flex-row', + 'type' => 'select_groups', + 'selected' => $values['id_group'], + 'return' => true, + 'class' => 'w50p', + ], + ]; + + $inputs[] = [ + 'label' => __('Product'), + 'id' => 'div-product', + 'arguments' => [ + 'name' => 'product', + 'input_class' => 'flex-row', + 'type' => 'select', + 'script' => 'calculate_inputs()', + 'fields' => [ + 'CUSTOM' => __('Custom'), + 'AWS' => __('Aws'), + 'AZURE' => __('Azure'), + // 'GOOGLE' => __('Google'), + ], + 'selected' => (isset($values['product']) ? $values['product'] : 'CUSTOM'), + 'disabled' => (bool) $values['product'], + 'return' => true, + ], + ]; + + $user_label = __('Username'); + $pass_label = __('Password'); + $extra_1_label = __('Extra'); + $extra_2_label = __('Extra (2)'); + $extra1 = true; + $extra2 = true; + + // Remember to update credential_store.php also. + switch ($values['product']) { + case 'AWS': + $user_label = __('Access key ID'); + $pass_label = __('Secret access key'); + $extra1 = false; + $extra2 = false; + break; + + case 'AZURE': + $user_label = __('Account ID'); + $pass_label = __('Application secret'); + $extra_1_label = __('Tenant or domain name'); + $extra_2_label = __('Subscription id'); + break; + + case 'GOOGLE': + // Need further investigation. + case 'CUSTOM': + $user_label = __('Account ID'); + $pass_label = __('Password'); + $extra1 = false; + $extra2 = false; + default: + // Use defaults. + break; + } + + $inputs[] = [ + 'label' => $user_label, + 'id' => 'div-username', + 'arguments' => [ + 'name' => 'username', + 'input_class' => 'flex-row', + 'type' => 'text', + 'value' => $values['username'], + 'return' => true, + ], + ]; + + $inputs[] = [ + 'label' => $pass_label, + 'id' => 'div-password', + 'arguments' => [ + 'name' => 'password', + 'input_class' => 'flex-row', + 'type' => 'password', + 'value' => $values['password'], + 'return' => true, + ], + ]; + + if ($extra1) { + $inputs[] = [ + 'label' => $extra_1_label, + 'id' => 'div-extra_1', + 'arguments' => [ + 'name' => 'extra_1', + 'input_class' => 'flex-row', + 'type' => 'text', + 'value' => $values['extra_1'], + 'return' => true, + ], + ]; + } + + if ($extra2) { + $inputs[] = [ + 'label' => $extra_2_label, + 'id' => 'div-extra_2', + 'arguments' => [ + 'name' => 'extra_2', + 'input_class' => 'flex-row', + 'type' => 'text', + 'value' => $values['extra_2'], + 'return' => true, + 'display' => $extra2, + ], + + ]; + } + + return $this->printForm( + [ + 'form' => $form, + 'inputs' => $inputs, + ], + true + ); + } + + + /** + * Loads JS content. + * + * @return string JS content. + */ + public function loadJS() + { + ob_start(); + + // Javascript content. + ?> + + url = ui_get_full_url( 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=hd' ); + + $this->access = 'AW'; $this->page = $page; $this->breadcrum = $breadcrum; } @@ -77,6 +79,8 @@ class CustomNetScan extends Wizard */ public function parseNetScan() { + global $config; + if (isset($this->page) === true && $this->page === 0) { // Check if we're updating a task. $task_id = get_parameter('task', null); @@ -145,11 +149,11 @@ class CustomNetScan extends Wizard ) { // Default values, no data received. // User is accesing directly to this page. - if (users_is_admin() !== true && check_acl( - $config['id_usuario'], + if (check_acl( + $config['id_user'], $this->task['id_group'], - 'PM' - ) !== true + $this->access + ) != true ) { $this->msg = __('You have no access to edit this task.'); return false; @@ -275,7 +279,7 @@ class CustomNetScan extends Wizard { global $config; - if (!check_acl($config['id_user'], 0, 'PM')) { + if (!check_acl($config['id_user'], 0, $this->access)) { db_pandora_audit( 'ACL Violation', 'Trying to access Custom Net Scan.' @@ -317,11 +321,11 @@ class CustomNetScan extends Wizard // Check ACL. If user is not able to manage target task, // redirect him to main page. - if (users_is_admin() !== true && check_acl( - $config['id_usuario'], + if (check_acl( + $config['id_user'], $this->task['id_group'], - 'PM' - ) !== true + $this->access + ) != true ) { $form['form']['action'] = $this->url.'&mode=customnetscan&page='.($this->page - 1); } @@ -496,7 +500,7 @@ class CustomNetScan extends Wizard 'arguments' => [ 'name' => 'id_group', 'returnAllGroup' => false, - 'privilege' => 'PM', + 'privilege' => $this->access, 'type' => 'select_groups', 'selected' => $this->task['id_group'], 'return' => true, diff --git a/pandora_console/include/class/ManageNetScanScripts.class.php b/pandora_console/include/class/ManageNetScanScripts.class.php index efc94cc8b6..c4a61bae37 100644 --- a/pandora_console/include/class/ManageNetScanScripts.class.php +++ b/pandora_console/include/class/ManageNetScanScripts.class.php @@ -65,6 +65,8 @@ class ManageNetScanScripts extends Wizard $this->url = ui_get_full_url( 'index.php?sec=gservers&sec2=godmode/servers/discovery&wiz=hd' ); + + $this->access = 'PM'; $this->page = $page; $this->breadcrum = $breadcrum; } @@ -81,7 +83,7 @@ class ManageNetScanScripts extends Wizard { global $config; - if (check_acl($config['id_user'], 0, 'AW') === 0) { + if (check_acl($config['id_user'], 0, $this->access) === 0) { db_pandora_audit( 'ACL Violation', 'Trying to access Net Scan Script.' diff --git a/pandora_console/include/class/NetworkMap.class.php b/pandora_console/include/class/NetworkMap.class.php index 0011167308..505d057665 100644 --- a/pandora_console/include/class/NetworkMap.class.php +++ b/pandora_console/include/class/NetworkMap.class.php @@ -2642,8 +2642,17 @@ class NetworkMap */ public function loadMapData() { + global $config; + $networkmap = $this->map; + // ACL. + $networkmap_write = check_acl( + $config['id_user'], + $networkmap['id_group'], + 'MW' + ); + $simulate = false; if (isset($networkmap['__simulated']) === false) { $networkmap['filter'] = json_decode( @@ -2711,6 +2720,7 @@ class NetworkMap $output .= 'var networkmap_center = [ '.$networkmap['center_x'].', '.$networkmap['center_y']."];\n"; $output .= 'var networkmap_dimensions = [ '.$networkmap['width'].', '.$networkmap['height']."];\n"; $output .= 'var enterprise_installed = '.((int) enterprise_installed()).";\n"; + $output .= 'var networkmap_write = '.$networkmap_write.";\n"; $output .= 'var node_radius = '.$networkmap['filter']['node_radius'].";\n"; $output .= 'var networkmap_holding_area_dimensions = '.json_encode($networkmap['filter']['holding_area']).";\n"; $output .= "var networkmap = {'nodes': [], 'links': []};\n"; diff --git a/pandora_console/include/class/Tree.class.php b/pandora_console/include/class/Tree.class.php index f5af14a6db..5c6434c8bd 100644 --- a/pandora_console/include/class/Tree.class.php +++ b/pandora_console/include/class/Tree.class.php @@ -1075,6 +1075,8 @@ class Tree ON ta.id_agente = tasg.id_agent LEFT JOIN talert_template_modules tatm ON tatm.id_agent_module = tam.id_agente_modulo + AND tatm.id_alert_template = 1 + OR tatm.id_alert_template = NULL $inner WHERE tam.disabled = 0 AND ta.disabled = 0 $condition diff --git a/pandora_console/include/class/TreeService.class.php b/pandora_console/include/class/TreeService.class.php index 251fde0d73..8e70fb4389 100644 --- a/pandora_console/include/class/TreeService.class.php +++ b/pandora_console/include/class/TreeService.class.php @@ -104,7 +104,7 @@ class TreeService extends Tree break; case SERVICE_STATUS_WARNING: - $processed_items[$row['id']][$key]['statusImageHTML'] = 'WARNING status.'; + $processed_items[$row['id']]['statusImageHTML'] = 'WARNING status.'; break; case SERVICE_STATUS_UNKNOWN: diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index b85e6ce713..484f8dd138 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -20,8 +20,8 @@ /** * Pandora build version and version */ -$build_version = 'PC190913'; -$pandora_version = 'v7.0NG.738'; +$build_version = 'PC191029'; +$pandora_version = 'v7.0NG.740'; // Do not overwrite default timezone set if defined. $script_tz = @date_default_timezone_get(); diff --git a/pandora_console/include/constants.php b/pandora_console/include/constants.php index c512c33c8f..8c5b1364f1 100644 --- a/pandora_console/include/constants.php +++ b/pandora_console/include/constants.php @@ -630,3 +630,21 @@ define('DEFAULT_NODE_COLOR', COL_NOTINIT); define('DEFAULT_NODE_IMAGE', 'images/networkmap/unknown.png'); define('NODE_IMAGE_PADDING', 5); + +// Pandora Database HA constants. +define('HA_ACTION_NONE', 0); +define('HA_ACTION_DEPLOY', 1); +define('HA_ACTION_RECOVER', 2); +define('HA_ACTION_PROMOTE', 3); +define('HA_ACTION_DEMOTE', 4); +define('HA_ACTION_DISABLE', 5); +define('HA_ACTION_ENABLE', 6); +define('HA_ACTION_CLEANUP', 7); +define('HA_ACTION_RESYNC', 8); + +define('HA_UNINITIALIZED', 0); +define('HA_ONLINE', 1); +define('HA_PENDING', 2); +define('HA_PROCESSING', 3); +define('HA_DISABLED', 4); +define('HA_FAILED', 5); diff --git a/pandora_console/include/functions.php b/pandora_console/include/functions.php index b1027bc4af..70eb7b8728 100644 --- a/pandora_console/include/functions.php +++ b/pandora_console/include/functions.php @@ -3789,11 +3789,20 @@ function series_type_graph_array($data, $show_elements_graph) } else if (strpos($key, 'percentil') !== false) { $data_return['series_type'][$key] = 'percentil'; if ($show_elements_graph['percentil']) { - $data_return['legend'][$key] = __('Percentil').' '.$config['percentil'].'º '.__('of module').' '; if ($show_elements_graph['unit']) { - $name_legend = $data_return['legend'][$key] = $value['agent_alias'].' / '.$value['module_name'].' / '.__('Unit ').' '.$show_elements_graph['unit'].': '; + $name_legend = __('Percentil').' '; + $name_legend .= $config['percentil'].'º '; + $name_legend .= __('of module').' '; + $name_legend .= $value['agent_alias'].' / '; + $name_legend .= $value['module_name'].' / '; + $name_legend .= __('Unit ').' '; + $name_legend .= $show_elements_graph['unit'].': '; } else { - $name_legend = $data_return['legend'][$key] = $value['agent_alias'].' / '.$value['module_name'].': '; + $name_legend = __('Percentil').' '; + $name_legend .= $config['percentil'].'º '; + $name_legend .= __('of module').' '; + $name_legend .= $value['agent_alias'].' / '; + $name_legend .= $value['module_name'].': '; } $data_return['legend'][$key] .= $name_legend; @@ -4086,7 +4095,7 @@ function mask2cidr($mask) function get_help_info($section_name) { global $config; - // hd($section_name); + $user_language = get_user_language($id_user); $es = false; @@ -5412,7 +5421,6 @@ function get_help_info($section_name) break; } - // hd($result); return $result; } diff --git a/pandora_console/include/functions_agents.php b/pandora_console/include/functions_agents.php index fdcce4457a..826ca971c5 100644 --- a/pandora_console/include/functions_agents.php +++ b/pandora_console/include/functions_agents.php @@ -68,6 +68,57 @@ function agents_get_agent_id_by_module_id($id_agente_modulo) } +/** + * Search for agent data anywhere. + * + * Note: This method matches with server (perl) locate_agent. + * Do not change order! + * + * @param string $field Alias, name or IP address of searchable agent. + * + * @return array Agent of false if not found. + */ +function agents_locate_agent(string $field) +{ + global $config; + + $table = 'tagente'; + if (is_metaconsole()) { + $table = 'tmetaconsole_agent'; + } + + // Alias. + $sql = sprintf( + 'SELECT * + FROM %s + WHERE alias = "%s"', + $table, + $field + ); + $agent = db_get_row_sql($sql); + + if ($agent !== false) { + return $agent; + } + + // Addr. + $agent = agents_get_agent_with_ip($field); + if ($agent !== false) { + return $agent; + } + + // Name. + $sql = sprintf( + 'SELECT * + FROM %s + WHERE nombre = "%s"', + $table, + $field + ); + return db_get_row_sql($sql); +} + + /** * Get agent id from an agent alias. * diff --git a/pandora_console/include/functions_api.php b/pandora_console/include/functions_api.php index 899add9ec0..5aa1020214 100644 --- a/pandora_console/include/functions_api.php +++ b/pandora_console/include/functions_api.php @@ -401,10 +401,11 @@ function api_get_groups($thrash1, $thrash2, $other, $returnType, $user_in_db) function api_get_agent_module_name_last_value($agentName, $moduleName, $other=';', $returnType) { $idAgent = agents_get_agent_id($agentName); + $sql = sprintf( 'SELECT id_agente_modulo - FROM tagente_modulo - WHERE id_agente = %d AND nombre LIKE "%s"', + FROM tagente_modulo + WHERE id_agente = %d AND nombre LIKE "%s"', $idAgent, $moduleName ); @@ -418,8 +419,8 @@ function api_get_agent_module_name_last_value_alias($alias, $moduleName, $other= { $sql = sprintf( 'SELECT tagente_modulo.id_agente_modulo FROM tagente_modulo - INNER JOIN tagente ON tagente_modulo.id_agente = tagente.id_agente - WHERE tagente.alias LIKE "%s" AND tagente_modulo.nombre LIKE "%s"', + INNER JOIN tagente ON tagente_modulo.id_agente = tagente.id_agente + WHERE tagente.alias LIKE "%s" AND tagente_modulo.nombre LIKE "%s"', $alias, $moduleName ); @@ -444,8 +445,8 @@ function api_get_module_last_value($idAgentModule, $trash1, $other=';', $returnT $sql = sprintf( 'SELECT datos - FROM tagente_estado - WHERE id_agente_modulo = %d', + FROM tagente_estado + WHERE id_agente_modulo = %d', $idAgentModule ); $value = db_get_value_sql($sql); @@ -892,9 +893,9 @@ function api_get_tree_agents($trash1, $trahs2, $other, $returnType) $id_group = $group['group_id']; $agents = db_get_all_rows_sql( "SELECT id_agente AS agent_id, id_grupo AS agent_id_group , alias $agent_additional_columns - FROM tagente ta LEFT JOIN tagent_secondary_group tasg - ON ta.id_agente = tasg.id_agent - WHERE ta.id_grupo = $id_group OR tasg.id_group = $id_group" + FROM tagente ta LEFT JOIN tagent_secondary_group tasg + ON ta.id_agente = tasg.id_agent + WHERE ta.id_grupo = $id_group OR tasg.id_group = $id_group" ); if ($agents === false) { $agents = []; @@ -916,13 +917,13 @@ function api_get_tree_agents($trash1, $trahs2, $other, $returnType) $modules = db_get_all_rows_sql( 'SELECT * - FROM (SELECT id_agente_modulo as module_id_agent_modulo '.$module_additional_columns.' - FROM tagente_modulo - WHERE id_agente = '.$agent['agent_id'].') t1 - INNER JOIN (SELECT id_agente_modulo as module_id_agent_modulo '.$estado_additional_columns.' - FROM tagente_estado - WHERE id_agente = '.$agent['agent_id'].') t2 - ON t1.module_id_agent_modulo = t2.module_id_agent_modulo' + FROM (SELECT id_agente_modulo as module_id_agent_modulo '.$module_additional_columns.' + FROM tagente_modulo + WHERE id_agente = '.$agent['agent_id'].') t1 + INNER JOIN (SELECT id_agente_modulo as module_id_agent_modulo '.$estado_additional_columns.' + FROM tagente_estado + WHERE id_agente = '.$agent['agent_id'].') t2 + ON t1.module_id_agent_modulo = t2.module_id_agent_modulo' ); if ($modules === false) { @@ -947,16 +948,16 @@ function api_get_tree_agents($trash1, $trahs2, $other, $returnType) $alerts = db_get_all_rows_sql( 'SELECT t1.id_agent_module as alert_id_agent_module '.$alert_additional_columns.' - FROM (SELECT * FROM talert_template_modules - WHERE id_agent_module = '.$module['module_id_agent_modulo'].') t1 - INNER JOIN talert_templates t2 - ON t1.id_alert_template = t2.id - LEFT JOIN talert_template_module_actions t3 - ON t1.id = t3.id_alert_template_module - LEFT JOIN talert_actions t4 - ON t3.id_alert_action = t4.id - LEFT JOIN talert_commands t5 - ON t4.id_alert_command = t5.id' + FROM (SELECT * FROM talert_template_modules + WHERE id_agent_module = '.$module['module_id_agent_modulo'].') t1 + INNER JOIN talert_templates t2 + ON t1.id_alert_template = t2.id + LEFT JOIN talert_template_module_actions t3 + ON t1.id = t3.id_alert_template_module + LEFT JOIN talert_actions t4 + ON t3.id_alert_action = t4.id + LEFT JOIN talert_commands t5 + ON t4.id_alert_command = t5.id' ); if ($alerts === false) { @@ -1141,8 +1142,8 @@ function api_get_module_properties_by_alias($alias, $module_name, $other, $retur $sql = sprintf( 'SELECT tagente_modulo.id_agente_modulo, tagente.id_agente FROM tagente_modulo - INNER JOIN tagente ON tagente_modulo.id_agente = tagente.id_agente - WHERE tagente.alias LIKE "%s" AND tagente_modulo.nombre LIKE "%s"', + INNER JOIN tagente ON tagente_modulo.id_agente = tagente.id_agente + WHERE tagente.alias LIKE "%s" AND tagente_modulo.nombre LIKE "%s"', $alias, $module_name ); @@ -1258,13 +1259,13 @@ function get_module_properties($id_module, $fields, $separator, $returnType, $re $returnVar = []; $modules = db_get_all_rows_sql( 'SELECT * - FROM (SELECT id_agente_modulo as module_id_agent_modulo '.$module_additional_columns.' - FROM tagente_modulo - WHERE id_agente_modulo = '.$id_module.') t1 - INNER JOIN (SELECT id_agente_modulo as module_id_agent_modulo '.$estado_additional_columns.' - FROM tagente_estado - WHERE id_agente_modulo = '.$id_module.') t2 - ON t1.module_id_agent_modulo = t2.module_id_agent_modulo' + FROM (SELECT id_agente_modulo as module_id_agent_modulo '.$module_additional_columns.' + FROM tagente_modulo + WHERE id_agente_modulo = '.$id_module.') t1 + INNER JOIN (SELECT id_agente_modulo as module_id_agent_modulo '.$estado_additional_columns.' + FROM tagente_estado + WHERE id_agente_modulo = '.$id_module.') t2 + ON t1.module_id_agent_modulo = t2.module_id_agent_modulo' ); if ($modules === false) { @@ -1328,8 +1329,8 @@ function api_set_update_agent($id_agent, $thrash2, $other, $thrash3) if ($cascadeProtection == 1) { if (($idParent != 0) && (db_get_value_sql( 'SELECT id_agente_modulo - FROM tagente_modulo - WHERE id_agente = '.$idParent.' AND id_agente_modulo = '.$cascadeProtectionModule + FROM tagente_modulo + WHERE id_agente = '.$idParent.' AND id_agente_modulo = '.$cascadeProtectionModule ) === false) ) { returnError('parent_agent_not_exist', 'Is not a parent module to do cascade protection.'); @@ -1368,7 +1369,7 @@ function api_set_update_agent($id_agent, $thrash2, $other, $thrash3) ); $tpolicy_group_old = db_get_all_rows_sql( 'SELECT id_policy FROM tpolicy_groups - WHERE id_group = '.$values_old['id_grupo'] + WHERE id_group = '.$values_old['id_grupo'] ); $return = db_process_sql_update( @@ -1413,7 +1414,7 @@ function api_set_update_agent($id_agent, $thrash2, $other, $thrash3) foreach ($tpolicy_group_old as $key => $value) { $tpolicy_agents_old = db_get_sql( 'SELECT * FROM tpolicy_agents - WHERE id_policy = '.$value['id_policy'].' AND id_agent = '.$id_agent + WHERE id_policy = '.$value['id_policy'].' AND id_agent = '.$id_agent ); if ($tpolicy_agents_old) { @@ -1431,14 +1432,14 @@ function api_set_update_agent($id_agent, $thrash2, $other, $thrash3) $tpolicy_group = db_get_all_rows_sql( 'SELECT id_policy FROM tpolicy_groups - WHERE id_group = '.$idGroup + WHERE id_group = '.$idGroup ); if ($tpolicy_group) { foreach ($tpolicy_group as $key => $value) { $tpolicy_agents = db_get_sql( 'SELECT * FROM tpolicy_agents - WHERE id_policy = '.$value['id_policy'].' AND id_agent ='.$id_agent + WHERE id_policy = '.$value['id_policy'].' AND id_agent ='.$id_agent ); if (!$tpolicy_agents) { @@ -1492,7 +1493,7 @@ function api_set_new_agent($thrash1, $thrash2, $other, $thrash3) global $config; if (!check_acl($config['id_user'], 0, 'AW')) { - returnError('forbidden', 'string'); + returnError('forbidden', 'you havent got permissions to do this'); return; } @@ -1500,127 +1501,101 @@ function api_set_new_agent($thrash1, $thrash2, $other, $thrash3) return; } - $alias = $other['data'][0]; - $ip = $other['data'][1]; - $idParent = $other['data'][2]; - $idGroup = $other['data'][3]; - $cascadeProtection = $other['data'][4]; - $cascadeProtectionModule = $other['data'][5]; - $intervalSeconds = $other['data'][6]; - $idOS = $other['data'][7]; - // $idServer = $other['data'][7]; - $nameServer = $other['data'][8]; - $customId = $other['data'][9]; - $learningMode = $other['data'][10]; - $disabled = $other['data'][11]; - $description = $other['data'][12]; - $alias_as_name = $other['data'][13]; + $alias = io_safe_input(trim(preg_replace('/[\/\\\|%#&$]/', '', $other['data'][0]))); + $direccion_agente = io_safe_input($other['data'][1]); + $nombre_agente = hash('sha256', $direccion_agente.'|'.$direccion_agente.'|'.time().'|'.sprintf('%04d', rand(0, 10000))); + $id_parent = (int) $other['data'][2]; + $grupo = (int) $other['data'][3]; + $cascade_protection = (int) $other['data'][4]; + $cascade_protection_module = (int) $other['data'][5]; + $intervalo = (string) $other['data'][6]; + $id_os = (int) $other['data'][7]; + $server_name = (string) $other['data'][8]; + $custom_id = (string) $other['data'][9]; + $modo = (int) $other['data'][10]; + $disabled = (int) $other['data'][11]; + $comentarios = (string) $other['data'][12]; + $alias_as_name = (int) $other['data'][13]; + $update_module_count = (int) $config['metaconsole_agent_cache'] == 1; - if ($alias_as_name && !empty($alias)) { - $name = $alias; - } else { - $name = hash('sha256', $alias.'|'.$direccion_agente.'|'.time().'|'.sprintf('%04d', rand(0, 10000))); - if (empty($alias)) { - $alias = $name; - } - } - - if ($cascadeProtection == 1) { - if (($idParent != 0) && (db_get_value_sql( + if ($cascade_protection == 1) { + if (($id_parent != 0) && (db_get_value_sql( 'SELECT id_agente_modulo - FROM tagente_modulo - WHERE id_agente = '.$idParent.' AND id_agente_modulo = '.$cascadeProtectionModule + FROM tagente_modulo + WHERE id_agente = '.$id_parent.' AND id_agente_modulo = '.$cascade_protection_module ) === false) ) { returnError('parent_agent_not_exist', 'Is not a parent module to do cascade protection.'); + return; } } else { $cascadeProtectionModule = 0; } - switch ($config['dbtype']) { - case 'mysql': - $sql1 = 'SELECT name - FROM tserver WHERE BINARY name LIKE "'.$nameServer.'"'; - break; + $server_name = db_get_value_sql('SELECT name FROM tserver WHERE BINARY name LIKE "'.$server_name.'"'); - case 'postgresql': - case 'oracle': - $sql1 = 'SELECT name - FROM tserver WHERE name LIKE \''.$nameServer.'\''; - break; - } - - $nameServer = db_get_value_sql($sql1); - - // Check ACL group - if (!check_acl($config['id_user'], $idGroup, 'AW')) { - returnError('forbidden', 'string'); - return; - } - - // Check selected parent - if ($idParent != 0) { - $parentCheck = agents_check_access_agent($idParent); - if ($parentCheck === null) { - returnError('parent_agent_not_exist', __('The agent parent don`t exist.')); - return; - } - - if ($parentCheck === false) { - returnError('parent_agent_forbidden', __('The user cannot access to parent agent.')); - return; - } - } - - if (agents_get_agent_id($name)) { + // Check if agent exists (BUG WC-50518-2). + if ($alias == '' && $alias_as_name === 0) { + returnError('alias_not_specified', 'No agent alias specified'); + } else if (agents_get_agent_id($name)) { returnError('agent_name_exist', 'The name of agent yet exist in DB.'); - } else if (db_get_value_sql( - 'SELECT id_grupo - FROM tgrupo - WHERE id_grupo = '.$idGroup - ) === false - ) { + } else if (db_get_value_sql('SELECT id_grupo FROM tgrupo WHERE id_grupo = '.$grupo) === false) { returnError('id_grupo_not_exist', 'The group don`t exist.'); - } else if (db_get_value_sql( - 'SELECT id_os - FROM tconfig_os - WHERE id_os = '.$idOS - ) === false - ) { + } else if (db_get_value_sql('SELECT id_os FROM tconfig_os WHERE id_os = '.$id_os) === false) { returnError('id_os_not_exist', 'The OS don`t exist.'); - } else if (db_get_value_sql($sql1) === false) { + } else if ($server_name === false) { returnError('server_not_exist', 'The '.get_product_name().' Server don`t exist.'); } else { - $idAgente = db_process_sql_insert( - 'tagente', - [ - 'nombre' => $name, - 'alias' => $alias, - 'direccion' => $ip, - 'id_grupo' => $idGroup, - 'intervalo' => $intervalSeconds, - 'comentarios' => $description, - 'modo' => $learningMode, - 'id_os' => $idOS, - 'disabled' => $disabled, - 'cascade_protection' => $cascadeProtection, - 'cascade_protection_module' => $cascadeProtectionModule, - 'server_name' => $nameServer, - 'id_parent' => $idParent, - 'custom_id' => $customId, - ] - ); - - if (!empty($idAgente) && !empty($ip)) { - // register ip for this agent in 'taddress' - agents_add_address($idAgente, $ip); + if ($alias_as_name === 1) { + $exists_alias = db_get_row_sql('SELECT nombre FROM tagente WHERE nombre = "'.$alias.'"'); + $nombre_agente = $alias; } - if ($idGroup && !empty($idAgente)) { + if ($direccion_agente != '') { + $exists_ip = db_get_row_sql('SELECT direccion FROM tagente WHERE direccion = "'.$direccion_agente.'"'); + } + + if (!$exists_alias && !$exists_ip) { + $id_agente = db_process_sql_insert( + 'tagente', + [ + 'nombre' => $nombre_agente, + 'alias' => $alias, + 'alias_as_name' => $alias_as_name, + 'direccion' => $direccion_agente, + 'id_grupo' => $grupo, + 'intervalo' => $intervalo, + 'comentarios' => $comentarios, + 'modo' => $modo, + 'id_os' => $id_os, + 'disabled' => $disabled, + 'cascade_protection' => $cascade_protection, + 'cascade_protection_module' => $cascade_protection_module, + 'server_name' => $server_name, + 'id_parent' => $id_parent, + 'custom_id' => $custom_id, + 'os_version' => '', + 'agent_version' => '', + 'timezone_offset' => 0, + 'icon_path' => '', + 'url_address' => '', + 'update_module_count' => $update_module_count, + ] + ); + enterprise_hook('update_agent', [$id_agente]); + } else { + $id_agente = false; + } + + if ($id_agente !== false) { + // Create address for this agent in taddress. + if ($direccion_agente != '') { + agents_add_address($id_agente, $direccion_agente); + } + $tpolicy_group_old = db_get_all_rows_sql( 'SELECT id_policy FROM tpolicy_groups - WHERE id_group = '.$idGroup + WHERE id_group = '.$grupo ); if ($tpolicy_group_old) { @@ -1629,18 +1604,54 @@ function api_set_new_agent($thrash1, $thrash2, $other, $thrash3) 'tpolicy_agents', [ 'id_policy' => $old_group['id_policy'], - 'id_agent' => $idAgente, + 'id_agent' => $id_agente, ] ); } } + + $info = '{"Name":"'.$nombre_agente.'", + "IP":"'.$direccion_agente.'", + "Group":"'.$grupo.'", + "Interval":"'.$intervalo.'", + "Comments":"'.$comentarios.'", + "Mode":"'.$modo.'", + "ID_parent:":"'.$id_parent.'", + "Server":"'.$server_name.'", + "ID os":"'.$id_os.'", + "Disabled":"'.$disabled.'", + "Custom ID":"'.$custom_id.'", + "Cascade protection":"'.$cascade_protection.'", + "Cascade protection module":"'.$cascade_protection_module.'"}'; + + $unsafe_alias = io_safe_output($alias); + db_pandora_audit( + 'Agent management', + 'Created agent '.$unsafe_alias, + false, + true, + $info + ); + } else { + $id_agente = 0; + + if ($exists_alias) { + $agent_creation_error = __('Could not be created, because name already exists'); + } else if ($exists_ip) { + $agent_creation_error = __('Could not be created, because IP already exists'); + } else { + $agent_creation_error = __('Could not be created for unknown reason'); + } + + returnError('generic error', $agent_creation_error); + return; } returnData( 'string', [ 'type' => 'string', - 'data' => $idAgente, + 'data' => $id_agente, ] ); } @@ -1803,17 +1814,23 @@ function api_get_custom_field_id($t1, $t2, $other, $returnType) /** - * Delete a agent with the name pass as parameter. + * Delete an agent with the name as parameter. * * @param string $id Name of agent to delete. * @param $thrash1 Don't use. * @param $thrast2 Don't use. * @param $thrash3 Don't use. */ -function api_set_delete_agent($id, $thrash1, $thrast2, $thrash3) +function api_set_delete_agent($id, $thrash1, $other, $thrash3) { global $config; + $agent_by_alias = false; + + if ($other['data'][0] === '1') { + $agent_by_alias = true; + } + if (is_metaconsole()) { if (!check_acl($config['id_user'], 0, 'PM')) { returnError('forbidden', 'string'); @@ -1822,8 +1839,8 @@ function api_set_delete_agent($id, $thrash1, $thrast2, $thrash3) $servers = db_get_all_rows_sql( 'SELECT * - FROM tmetaconsole_setup - WHERE disabled = 0' + FROM tmetaconsole_setup + WHERE disabled = 0' ); if ($servers === false) { @@ -1832,19 +1849,47 @@ function api_set_delete_agent($id, $thrash1, $thrast2, $thrash3) foreach ($servers as $server) { if (metaconsole_connect($server) == NOERR) { - $idAgent[0] = agents_get_agent_id($id, true); + if ($other['data'][0] === '1') { + $idAgent[0] = agents_get_agent_id_by_alias($id); + } else { + $idAgent[0] = agents_get_agent_id($id, true); + } + if ($idAgent[0]) { $result = agents_delete_agent($idAgent, true); } + + metaconsole_restore_db(); } } } else { - $idAgent = agents_get_agent_id($id); - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AD')) { - return; + if ($agent_by_alias) { + $idsAgents = agents_get_agent_id_by_alias(io_safe_input($id)); + } else { + $idAgent = agents_get_agent_id($id, true); } - $result = agents_delete_agent($idAgent, true); + if (!$agent_by_alias) { + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AD')) { + return; + } + } + + if ($agent_by_alias) { + foreach ($idsAgents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AD')) { + continue; + } + + $result = agents_delete_agent($id['id_agente'], true); + + if (!$result) { + break; + } + } + } else { + $result = agents_delete_agent($idAgent, true); + } } if (!$result) { @@ -1931,20 +1976,20 @@ function api_get_all_agents($thrash1, $thrash2, $other, $returnType) // Filter by state if (defined('METACONSOLE')) { $sql = "SELECT id_agente, alias, direccion, comentarios, - tconfig_os.name, url_address, nombre - FROM tconfig_os, tmetaconsole_agent - LEFT JOIN tagent_secondary_group - ON tmetaconsole_agent.id_agente = tagent_secondary_group.id_agent - WHERE tmetaconsole_agent.id_os = tconfig_os.id_os - AND disabled = 0 $where AND $groups"; + tconfig_os.name, url_address, nombre + FROM tconfig_os, tmetaconsole_agent + LEFT JOIN tagent_secondary_group + ON tmetaconsole_agent.id_agente = tagent_secondary_group.id_agent + WHERE tmetaconsole_agent.id_os = tconfig_os.id_os + AND disabled = 0 $where AND $groups"; } else { $sql = "SELECT id_agente, alias, direccion, comentarios, - tconfig_os.name, url_address, nombre - FROM tconfig_os, tagente - LEFT JOIN tagent_secondary_group - ON tagente.id_agente = tagent_secondary_group.id_agent - WHERE tagente.id_os = tconfig_os.id_os - AND disabled = 0 $where AND $groups"; + tconfig_os.name, url_address, nombre + FROM tconfig_os, tagente + LEFT JOIN tagent_secondary_group + ON tagente.id_agente = tagent_secondary_group.id_agent + WHERE tagente.id_os = tconfig_os.id_os + AND disabled = 0 $where AND $groups"; } $all_agents = db_get_all_rows_sql($sql); @@ -2068,9 +2113,9 @@ function api_get_agent_modules($thrash1, $thrash2, $other, $thrash3) $sql = sprintf( 'SELECT id_agente, id_agente_modulo, nombre - FROM tagente_modulo - WHERE id_agente = %d AND disabled = 0 - AND delete_pending = 0', + FROM tagente_modulo + WHERE id_agente = %d AND disabled = 0 + AND delete_pending = 0', $other['data'][0] ); @@ -2417,9 +2462,9 @@ function api_get_module_id($id, $thrash1, $name, $thrash3) $sql = sprintf( 'SELECT id_agente_modulo - FROM tagente_modulo WHERE id_agente = %d - AND nombre = "%s" AND disabled = 0 - AND delete_pending = 0', + FROM tagente_modulo WHERE id_agente = %d + AND nombre = "%s" AND disabled = 0 + AND delete_pending = 0', $id, $name['data'] ); @@ -2459,10 +2504,10 @@ function api_get_group_agent($thrash1, $thrash2, $other, $thrash3) $sql = sprintf( 'SELECT groups.nombre nombre - FROM tagente agents, tgrupo groups - WHERE id_agente = %d AND agents.disabled = 0 - AND groups.disabled = 0 - AND agents.id_grupo = groups.id_grupo', + FROM tagente agents, tgrupo groups + WHERE id_agente = %d AND agents.disabled = 0 + AND groups.disabled = 0 + AND agents.id_grupo = groups.id_grupo', $other['data'][0] ); @@ -2501,8 +2546,8 @@ function api_get_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) if (is_metaconsole()) { $servers = db_get_all_rows_sql( 'SELECT * - FROM tmetaconsole_setup - WHERE disabled = 0' + FROM tmetaconsole_setup + WHERE disabled = 0' ); if ($servers === false) { @@ -2516,9 +2561,9 @@ function api_get_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) if ($agent_id) { $sql = sprintf( 'SELECT groups.nombre nombre - FROM tagente agents, tgrupo groups - WHERE id_agente = %d - AND agents.id_grupo = groups.id_grupo', + FROM tagente agents, tgrupo groups + WHERE id_agente = %d + AND agents.id_grupo = groups.id_grupo', $agent_id ); $group_server_names = db_get_all_rows_sql($sql); @@ -2541,9 +2586,9 @@ function api_get_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) $sql = sprintf( 'SELECT groups.nombre nombre - FROM tagente agents, tgrupo groups - WHERE id_agente = %d - AND agents.id_grupo = groups.id_grupo', + FROM tagente agents, tgrupo groups + WHERE id_agente = %d + AND agents.id_grupo = groups.id_grupo', $agent_id ); $group_names = db_get_all_rows_sql($sql); @@ -2593,8 +2638,8 @@ function api_get_group_agent_by_alias($thrash1, $thrash2, $other, $thrash3) if (is_metaconsole()) { $servers = db_get_all_rows_sql( 'SELECT * - FROM tmetaconsole_setup - WHERE disabled = 0' + FROM tmetaconsole_setup + WHERE disabled = 0' ); if ($servers === false) { @@ -2609,9 +2654,9 @@ function api_get_group_agent_by_alias($thrash1, $thrash2, $other, $thrash3) foreach ($agent_id as &$id) { $sql = sprintf( 'SELECT groups.nombre nombre - FROM tagente agents, tgrupo groups - WHERE id_agente = %d - AND agents.id_grupo = groups.id_grupo', + FROM tagente agents, tgrupo groups + WHERE id_agente = %d + AND agents.id_grupo = groups.id_grupo', $id['id_agente'] ); $group_server_names = db_get_all_rows_sql($sql); @@ -2637,9 +2682,9 @@ function api_get_group_agent_by_alias($thrash1, $thrash2, $other, $thrash3) $sql = sprintf( 'SELECT groups.nombre nombre - FROM tagente agents, tgrupo groups - WHERE id_agente = %d - AND agents.id_grupo = groups.id_grupo', + FROM tagente agents, tgrupo groups + WHERE id_agente = %d + AND agents.id_grupo = groups.id_grupo', $id['id_agente'] ); $group_name = db_get_all_rows_sql($sql); @@ -2682,8 +2727,8 @@ function api_get_locate_agent($id, $thrash1, $thrash2, $thrash3) $servers = db_get_all_rows_sql( 'SELECT * - FROM tmetaconsole_setup - WHERE disabled = 0' + FROM tmetaconsole_setup + WHERE disabled = 0' ); if ($servers === false) { @@ -2740,8 +2785,8 @@ function api_get_id_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) if (is_metaconsole()) { $servers = db_get_all_rows_sql( 'SELECT * - FROM tmetaconsole_setup - WHERE disabled = 0' + FROM tmetaconsole_setup + WHERE disabled = 0' ); if ($servers === false) { @@ -2755,9 +2800,9 @@ function api_get_id_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) if ($agent_id) { $sql = sprintf( 'SELECT groups.id_grupo id_group - FROM tagente agents, tgrupo groups - WHERE id_agente = %d - AND agents.id_grupo = groups.id_grupo', + FROM tagente agents, tgrupo groups + WHERE id_agente = %d + AND agents.id_grupo = groups.id_grupo', $agent_id ); $group_server_names = db_get_all_rows_sql($sql); @@ -2781,9 +2826,9 @@ function api_get_id_group_agent_by_name($thrash1, $thrash2, $other, $thrash3) $sql = sprintf( 'SELECT groups.id_grupo id_group - FROM tagente agents, tgrupo groups - WHERE id_agente = %d - AND agents.id_grupo = groups.id_grupo', + FROM tagente agents, tgrupo groups + WHERE id_agente = %d + AND agents.id_grupo = groups.id_grupo', $agent_id ); $group_names = db_get_all_rows_sql($sql); @@ -2833,8 +2878,8 @@ function api_get_id_group_agent_by_alias($thrash1, $thrash2, $other, $thrash3) if (is_metaconsole()) { $servers = db_get_all_rows_sql( 'SELECT * - FROM tmetaconsole_setup - WHERE disabled = 0' + FROM tmetaconsole_setup + WHERE disabled = 0' ); if ($servers === false) { @@ -2849,9 +2894,9 @@ function api_get_id_group_agent_by_alias($thrash1, $thrash2, $other, $thrash3) foreach ($agent_id as &$id) { $sql = sprintf( 'SELECT groups.id_grupo id_group - FROM tagente agents, tgrupo groups - WHERE id_agente = %d - AND agents.id_grupo = groups.id_grupo', + FROM tagente agents, tgrupo groups + WHERE id_agente = %d + AND agents.id_grupo = groups.id_grupo', $id['id_agente'] ); $group_server_names = db_get_all_rows_sql($sql); @@ -2877,9 +2922,9 @@ function api_get_id_group_agent_by_alias($thrash1, $thrash2, $other, $thrash3) $sql = sprintf( 'SELECT groups.id_grupo id_group - FROM tagente agents, tgrupo groups - WHERE id_agente = %d - AND agents.id_grupo = groups.id_grupo', + FROM tagente agents, tgrupo groups + WHERE id_agente = %d + AND agents.id_grupo = groups.id_grupo', $id['id_agente'] ); $group_name = db_get_all_rows_sql($sql); @@ -2937,8 +2982,8 @@ function api_get_policies($thrash1, $thrash2, $other, $thrash3) $sql = sprintf( 'SELECT policy.id, name, id_agent - FROM tpolicies AS policy, tpolicy_agents AS pol_agents - WHERE policy.id = pol_agents.id_policy %s AND id_group IN (%s)', + FROM tpolicies AS policy, tpolicy_agents AS pol_agents + WHERE policy.id = pol_agents.id_policy %s AND id_group IN (%s)', $where, $user_groups ); @@ -3036,12 +3081,22 @@ function api_set_create_network_module($id, $thrash1, $other, $thrash3) return; } - $agentName = $id; + $agent_by_alias = false; - $idAgent = agents_get_agent_id($agentName); + if ($other['data'][30] === '1') { + $agent_by_alias = true; + } - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { - return; + if ($agent_by_alias) { + $idsAgents = agents_get_agent_id_by_alias($id); + } else { + $idAgent = agents_get_agent_id($id); + } + + if (!$agent_by_alias) { + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { + return; + } } if ($other['data'][2] < 6 or $other['data'][2] > 18) { @@ -3059,7 +3114,6 @@ function api_set_create_network_module($id, $thrash1, $other, $thrash3) $disabled_types_event = json_encode($disabled_types_event); $values = [ - 'id_agente' => $idAgent, 'disabled' => $other['data'][1], 'id_tipo_modulo' => $other['data'][2], 'id_module_group' => $other['data'][3], @@ -3102,7 +3156,27 @@ function api_set_create_network_module($id, $thrash1, $other, $thrash3) // Column 'module_macros' cannot be null } - $idModule = modules_create_agent_module($idAgent, $name, $values, true); + if ($agent_by_alias) { + $agents_affected = 0; + + foreach ($idsAgents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AW')) { + continue; + } + + $idModule = modules_create_agent_module($id['id_agente'], $name, $values, true); + + if (!is_error($idModule)) { + $agents_affected++; + } + } + + returnData('string', ['type' => 'string', 'data' => $agents_affected.' agents affected']); + + return; + } else { + $idModule = modules_create_agent_module($idAgent, $name, $values, true); + } if (is_error($idModule)) { // TODO: Improve the error returning more info @@ -3270,17 +3344,27 @@ function api_set_create_plugin_module($id, $thrash1, $other, $thrash3) return; } - $agentName = $id; - if ($other['data'][22] == '') { returnError('error_create_plugin_module', __('Error in creation plugin module. Id_plugin cannot be left blank.')); return; } - $idAgent = agents_get_agent_id($agentName); + $agent_by_alias = false; - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { - return; + if ($other['data'][36] === '1') { + $agent_by_alias = true; + } + + if ($agent_by_alias) { + $idsAgents = agents_get_agent_id_by_alias($id); + } else { + $idAgent = agents_get_agent_id($id); + } + + if (!$agent_by_alias) { + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { + return; + } } $disabled_types_event = []; @@ -3290,7 +3374,6 @@ function api_set_create_plugin_module($id, $thrash1, $other, $thrash3) $name = $other['data'][0]; $values = [ - 'id_agente' => $idAgent, 'disabled' => $other['data'][1], 'id_tipo_modulo' => $other['data'][2], 'id_module_group' => $other['data'][3], @@ -3338,7 +3421,27 @@ function api_set_create_plugin_module($id, $thrash1, $other, $thrash3) // Column 'module_macros' cannot be null } - $idModule = modules_create_agent_module($idAgent, $name, $values, true); + if ($agent_by_alias) { + $agents_affected = 0; + + foreach ($idsAgents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AW')) { + continue; + } + + $idModule = modules_create_agent_module($id['id_agente'], $name, $values, true); + + if (!is_error($idModule)) { + $agents_affected++; + } + } + + returnData('string', ['type' => 'string', 'data' => $agents_affected.' agents affected']); + + return; + } else { + $idModule = modules_create_agent_module($idAgent, $name, $values, true); + } if (is_error($idModule)) { // TODO: Improve the error returning more info @@ -3499,17 +3602,27 @@ function api_set_create_data_module($id, $thrash1, $other, $thrash3) return; } - $agentName = $id; - if ($other['data'][0] == '') { returnError('error_create_data_module', __('Error in creation data module. Module_name cannot be left blank.')); return; } - $idAgent = agents_get_agent_id($agentName); + $agent_by_alias = false; - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { - return; + if ($other['data'][27] === '1') { + $agent_by_alias = true; + } + + if ($agent_by_alias) { + $idsAgents = agents_get_agent_id_by_alias($id); + } else { + $idAgent = agents_get_agent_id($id); + } + + if (!$agent_by_alias) { + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { + return; + } } $name = $other['data'][0]; @@ -3519,7 +3632,6 @@ function api_set_create_data_module($id, $thrash1, $other, $thrash3) $disabled_types_event = json_encode($disabled_types_event); $values = [ - 'id_agente' => $idAgent, 'disabled' => $other['data'][1], 'id_tipo_modulo' => $other['data'][2], 'descripcion' => $other['data'][3], @@ -3558,7 +3670,27 @@ function api_set_create_data_module($id, $thrash1, $other, $thrash3) // Column 'module_macros' cannot be null } - $idModule = modules_create_agent_module($idAgent, $name, $values, true); + if ($agent_by_alias) { + $agents_affected = 0; + + foreach ($idsAgents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AW')) { + continue; + } + + $idModule = modules_create_agent_module($id['id_agente'], $name, $values, true); + + if (!is_error($idModule)) { + $agents_affected++; + } + } + + returnData('string', ['type' => 'string', 'data' => $agents_affected.' agents affected']); + + return; + } else { + $idModule = modules_create_agent_module($idAgent, $name, $values, true); + } if (is_error($idModule)) { // TODO: Improve the error returning more info @@ -3583,7 +3715,7 @@ function api_set_create_data_module($id, $thrash1, $other, $thrash3) * * @param $thrash3 Don't use */ -function api_set_create_synthetic_module($id, $thrash1, $other, $thrash3) +function api_set_create_synthetic_module($id, $agent_by_alias, $other, $thrash3) { if (defined('METACONSOLE')) { return; @@ -3591,8 +3723,6 @@ function api_set_create_synthetic_module($id, $thrash1, $other, $thrash3) global $config; - $agentName = $id; - io_safe_input_array($other); if ($other['data'][0] == '') { @@ -3600,15 +3730,34 @@ function api_set_create_synthetic_module($id, $thrash1, $other, $thrash3) return; } - $idAgent = agents_get_agent_id(io_safe_output($agentName), true); + if ($agent_by_alias == '1') { + $ids_agents = agents_get_agent_id_by_alias(io_safe_output($id)); - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { - return; + foreach ($ids_agents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AW')) { + return; + } + } + } else { + $idAgent = agents_get_agent_id(io_safe_output($id), true); + + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { + return; + } } - if (!$idAgent) { - returnError('error_create_data_module', __('Error in creation synthetic module. Agent name doesn\'t exist.')); - return; + if ($agent_by_alias) { + foreach ($ids_agents as $id) { + if (!$id['id_agente']) { + returnError('error_create_data_module', __('Error in creation synthetic module. Agent name doesn\'t exist.')); + return; + } + } + } else { + if (!$idAgent) { + returnError('error_create_data_module', __('Error in creation synthetic module. Agent name doesn\'t exist.')); + return; + } } $name = io_safe_output($other['data'][0]); @@ -3616,7 +3765,6 @@ function api_set_create_synthetic_module($id, $thrash1, $other, $thrash3) $id_tipo_modulo = db_get_row_sql("SELECT id_tipo FROM ttipo_modulo WHERE nombre = 'generic_data'"); $values = [ - 'id_agente' => $idAgent, 'id_modulo' => 5, 'custom_integer_1' => 0, 'custom_integer_2' => 0, @@ -3629,151 +3777,312 @@ function api_set_create_synthetic_module($id, $thrash1, $other, $thrash3) // Column 'descripcion' cannot be null } - $idModule = modules_create_agent_module($idAgent, $name, $values, true); + if ($agent_by_alias) { + foreach ($ids_agents as $id) { + $idAgent = $id['id_agente']; - if (is_error($idModule)) { - // TODO: Improve the error returning more info - returnError('error_create_data_module', __('Error in creation data module.')); - } else { - $synthetic_type = $other['data'][1]; - unset($other['data'][0]); - unset($other['data'][1]); + $idModule = modules_create_agent_module($idAgent, $name, $values, true); - $filterdata = []; - foreach ($other['data'] as $data) { - $data = str_replace(['ADD', 'SUB', 'MUL', 'DIV'], ['+', '-', '*', '/'], $data); - $split_data = explode(';', $data); + if (is_error($idModule)) { + // TODO: Improve the error returning more info + returnError('error_create_data_module', __('Error in creation data module.')); + } else { + $synthetic_type = $other['data'][1]; + unset($other['data'][0]); + unset($other['data'][1]); - if (preg_match('/[x\/+*-]/', $split_data[0]) && strlen($split_data[0]) == 1) { - if (preg_match('/[\/|+|*|-]/', $split_data[0]) && $synthetic_type === 'average') { - returnError('', "[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); + $filterdata = []; + foreach ($other['data'] as $data) { + $data = str_replace(['ADD', 'SUB', 'MUL', 'DIV'], ['+', '-', '*', '/'], $data); + $data = io_safe_output($data); + // Double safe output is necessary. + $split_data = explode(';', io_safe_output($data)); + + if (preg_match('/[x\/+*-]/', $split_data[0]) && strlen($split_data[0]) == 1) { + if (preg_match('/[\/|+|*|-]/', $split_data[0]) && $synthetic_type === 'average') { + returnError('', "[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); + } + + $operator = strtolower($split_data[0]); + $data_module = [ + '', + $operator, + $split_data[1], + ]; + + $text_data = implode('_', $data_module); + array_push($filterdata, $text_data); + } else { + if (count($split_data) == 2) { + $idAgent = agents_get_agent_id($split_data[0], true); + $data_module = [ + $idAgent, + '', + $split_data[1], + ]; + $text_data = implode('_', $data_module); + array_push($filterdata, $text_data); + } else { + if (strlen($split_data[1]) > 1 && $synthetic_type != 'average') { + returnError('', "[ERROR] You can only use +, -, *, / or x, and you use this: @split_data[1] \n\n"); + return; + } + + if (preg_match('/[\/|+|*|-]/', $split_data[1]) && $synthetic_type === 'average') { + returnError('', "[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); + return; + } + + $idAgent = agents_get_agent_id(io_safe_output($split_data[0]), true); + $operator = strtolower($split_data[1]); + $data_module = [ + $idAgent, + $operator, + $split_data[2], + ]; + $text_data = implode('_', $data_module); + array_push($filterdata, $text_data); + } + } } - $operator = strtolower($split_data[0]); - $data_module = [ - '', - $operator, - $split_data[1], - ]; + $serialize_ops = implode(',', $filterdata); - $text_data = implode('_', $data_module); - array_push($filterdata, $text_data); - } else { - if (count($split_data) == 2) { - $idAgent = agents_get_agent_id(io_safe_output($split_data[0]), true); - $data_module = [ - $idAgent, - '', - $split_data[1], - ]; - $text_data = implode('_', $data_module); - array_push($filterdata, $text_data); + // modules_create_synthetic_operations + $synthetic = enterprise_hook( + 'modules_create_synthetic_operations', + [ + $idModule, + $serialize_ops, + ] + ); + + if ($synthetic === ENTERPRISE_NOT_HOOK) { + returnError('error_synthetic_modules', 'Error Synthetic modules.'); + db_process_sql_delete( + 'tagente_modulo', + ['id_agente_modulo' => $idModule] + ); + + return; } else { - if (strlen($split_data[1]) > 1 && $synthetic_type != 'average') { - returnError('', "[ERROR] You can only use +, -, *, / or x, and you use this: @split_data[1] \n\n"); - return; + $status = AGENT_MODULE_STATUS_NO_DATA; + switch ($config['dbtype']) { + case 'mysql': + $result = db_process_sql_insert( + 'tagente_estado', + [ + 'id_agente_modulo' => $idModule, + 'datos' => 0, + 'timestamp' => '01-01-1970 00:00:00', + 'estado' => $status, + 'id_agente' => (int) $idAgent, + 'utimestamp' => 0, + 'status_changes' => 0, + 'last_status' => $status, + 'last_known_status' => $status, + ] + ); + break; + + case 'postgresql': + $result = db_process_sql_insert( + 'tagente_estado', + [ + 'id_agente_modulo' => $idModule, + 'datos' => 0, + 'timestamp' => null, + 'estado' => $status, + 'id_agente' => (int) $idAgent, + 'utimestamp' => 0, + 'status_changes' => 0, + 'last_status' => $status, + 'last_known_status' => $status, + ] + ); + break; + + case 'oracle': + $result = db_process_sql_insert( + 'tagente_estado', + [ + 'id_agente_modulo' => $idModule, + 'datos' => 0, + 'timestamp' => '#to_date(\'1970-01-01 00:00:00\', \'YYYY-MM-DD HH24:MI:SS\')', + 'estado' => $status, + 'id_agente' => (int) $idAgent, + 'utimestamp' => 0, + 'status_changes' => 0, + 'last_status' => $status, + 'last_known_status' => $status, + ] + ); + break; } - if (preg_match('/[\/|+|*|-]/', $split_data[1]) && $synthetic_type === 'average') { - returnError('', "[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); - return; + if ($result === false) { + db_process_sql_delete( + 'tagente_modulo', + ['id_agente_modulo' => $idModule] + ); + returnError('error_synthetic_modules', 'Error Synthetic modules.'); + } else { + db_process_sql('UPDATE tagente SET total_count=total_count+1, notinit_count=notinit_count+1 WHERE id_agente='.(int) $idAgent); + returnData('string', ['type' => 'string', 'data' => __('Synthetic module created ID: '.$idModule)]); } - - $idAgent = agents_get_agent_id(io_safe_output($split_data[0]), true); - $operator = strtolower($split_data[1]); - $data_module = [ - $idAgent, - $operator, - $split_data[2], - ]; - $text_data = implode('_', $data_module); - array_push($filterdata, $text_data); } } } + } else { + $idModule = modules_create_agent_module($idAgent, $name, $values, true); - $serialize_ops = implode(',', $filterdata); - - // modules_create_synthetic_operations - $synthetic = enterprise_hook( - 'modules_create_synthetic_operations', - [ - $idModule, - $serialize_ops, - ] - ); - - if ($synthetic === ENTERPRISE_NOT_HOOK) { - returnError('error_synthetic_modules', 'Error Synthetic modules.'); - db_process_sql_delete( - 'tagente_modulo', - ['id_agente_modulo' => $idModule] - ); - return; + if (is_error($idModule)) { + // TODO: Improve the error returning more info + returnError('error_create_data_module', __('Error in creation data module.')); } else { - $status = AGENT_MODULE_STATUS_NO_DATA; - switch ($config['dbtype']) { - case 'mysql': - $result = db_process_sql_insert( - 'tagente_estado', - [ - 'id_agente_modulo' => $idModule, - 'datos' => 0, - 'timestamp' => '01-01-1970 00:00:00', - 'estado' => $status, - 'id_agente' => (int) $idAgent, - 'utimestamp' => 0, - 'status_changes' => 0, - 'last_status' => $status, - 'last_known_status' => $status, - ] - ); - break; + $synthetic_type = $other['data'][1]; + unset($other['data'][0]); + unset($other['data'][1]); - case 'postgresql': - $result = db_process_sql_insert( - 'tagente_estado', - [ - 'id_agente_modulo' => $idModule, - 'datos' => 0, - 'timestamp' => null, - 'estado' => $status, - 'id_agente' => (int) $idAgent, - 'utimestamp' => 0, - 'status_changes' => 0, - 'last_status' => $status, - 'last_known_status' => $status, - ] - ); - break; + $filterdata = []; + foreach ($other['data'] as $data) { + $data = str_replace(['ADD', 'SUB', 'MUL', 'DIV'], ['+', '-', '*', '/'], $data); + $data = io_safe_output($data); + // Double safe output is necessary. + $split_data = explode(';', io_safe_output($data)); - case 'oracle': - $result = db_process_sql_insert( - 'tagente_estado', - [ - 'id_agente_modulo' => $idModule, - 'datos' => 0, - 'timestamp' => '#to_date(\'1970-01-01 00:00:00\', \'YYYY-MM-DD HH24:MI:SS\')', - 'estado' => $status, - 'id_agente' => (int) $idAgent, - 'utimestamp' => 0, - 'status_changes' => 0, - 'last_status' => $status, - 'last_known_status' => $status, - ] - ); - break; + if (preg_match('/[x\/+*-]/', $split_data[0]) && strlen($split_data[0]) == 1) { + if (preg_match('/[\/|+|*|-]/', $split_data[0]) && $synthetic_type === 'average') { + returnError('', "[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); + } + + $operator = strtolower($split_data[0]); + $data_module = [ + '', + $operator, + $split_data[1], + ]; + + $text_data = implode('_', $data_module); + array_push($filterdata, $text_data); + } else { + if (count($split_data) == 2) { + $idAgent = agents_get_agent_id($split_data[0], true); + $data_module = [ + $idAgent, + '', + $split_data[1], + ]; + $text_data = implode('_', $data_module); + array_push($filterdata, $text_data); + } else { + if (strlen($split_data[1]) > 1 && $synthetic_type != 'average') { + returnError('', "[ERROR] You can only use +, -, *, / or x, and you use this: @split_data[1] \n\n"); + return; + } + + if (preg_match('/[\/|+|*|-]/', $split_data[1]) && $synthetic_type === 'average') { + returnError('', "[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); + return; + } + + $idAgent = agents_get_agent_id(io_safe_output($split_data[0]), true); + $operator = strtolower($split_data[1]); + $data_module = [ + $idAgent, + $operator, + $split_data[2], + ]; + $text_data = implode('_', $data_module); + array_push($filterdata, $text_data); + } + } } - if ($result === false) { + $serialize_ops = implode(',', $filterdata); + + // modules_create_synthetic_operations + $synthetic = enterprise_hook( + 'modules_create_synthetic_operations', + [ + $idModule, + $serialize_ops, + ] + ); + + if ($synthetic === ENTERPRISE_NOT_HOOK) { + returnError('error_synthetic_modules', 'Error Synthetic modules.'); db_process_sql_delete( 'tagente_modulo', ['id_agente_modulo' => $idModule] ); - returnError('error_synthetic_modules', 'Error Synthetic modules.'); + + return; } else { - db_process_sql('UPDATE tagente SET total_count=total_count+1, notinit_count=notinit_count+1 WHERE id_agente='.(int) $idAgent); - returnData('string', ['type' => 'string', 'data' => __('Synthetic module created ID: '.$idModule)]); + $status = AGENT_MODULE_STATUS_NO_DATA; + switch ($config['dbtype']) { + case 'mysql': + $result = db_process_sql_insert( + 'tagente_estado', + [ + 'id_agente_modulo' => $idModule, + 'datos' => 0, + 'timestamp' => '01-01-1970 00:00:00', + 'estado' => $status, + 'id_agente' => (int) $idAgent, + 'utimestamp' => 0, + 'status_changes' => 0, + 'last_status' => $status, + 'last_known_status' => $status, + ] + ); + break; + + case 'postgresql': + $result = db_process_sql_insert( + 'tagente_estado', + [ + 'id_agente_modulo' => $idModule, + 'datos' => 0, + 'timestamp' => null, + 'estado' => $status, + 'id_agente' => (int) $idAgent, + 'utimestamp' => 0, + 'status_changes' => 0, + 'last_status' => $status, + 'last_known_status' => $status, + ] + ); + break; + + case 'oracle': + $result = db_process_sql_insert( + 'tagente_estado', + [ + 'id_agente_modulo' => $idModule, + 'datos' => 0, + 'timestamp' => '#to_date(\'1970-01-01 00:00:00\', \'YYYY-MM-DD HH24:MI:SS\')', + 'estado' => $status, + 'id_agente' => (int) $idAgent, + 'utimestamp' => 0, + 'status_changes' => 0, + 'last_status' => $status, + 'last_known_status' => $status, + ] + ); + break; + } + + if ($result === false) { + db_process_sql_delete( + 'tagente_modulo', + ['id_agente_modulo' => $idModule] + ); + returnError('error_synthetic_modules', 'Error Synthetic modules.'); + } else { + db_process_sql('UPDATE tagente SET total_count=total_count+1, notinit_count=notinit_count+1 WHERE id_agente='.(int) $idAgent); + returnData('string', ['type' => 'string', 'data' => __('Synthetic module created ID: '.$idModule)]); + } } } } @@ -3923,8 +4232,6 @@ function api_set_create_snmp_module($id, $thrash1, $other, $thrash3) return; } - $agentName = $id; - if ($other['data'][0] == '') { returnError('error_create_snmp_module', __('Error in creation SNMP module. Module_name cannot be left blank.')); return; @@ -3935,10 +4242,22 @@ function api_set_create_snmp_module($id, $thrash1, $other, $thrash3) return; } - $idAgent = agents_get_agent_id($agentName); + $agent_by_alias = false; - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { - return; + if ($other['data'][35] === '1') { + $agent_by_alias = true; + } + + if ($agent_by_alias) { + $idsAgents = agents_get_agent_id_by_alias($id); + } else { + $idAgent = agents_get_agent_id($id); + } + + if (!$agent_by_alias) { + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { + return; + } } $name = $other['data'][0]; @@ -3965,7 +4284,6 @@ function api_set_create_snmp_module($id, $thrash1, $other, $thrash3) } $values = [ - 'id_agente' => $idAgent, 'disabled' => $other['data'][1], 'id_tipo_modulo' => $other['data'][2], 'id_module_group' => $other['data'][3], @@ -4003,7 +4321,6 @@ function api_set_create_snmp_module($id, $thrash1, $other, $thrash3) ]; } else { $values = [ - 'id_agente' => $idAgent, 'disabled' => $other['data'][1], 'id_tipo_modulo' => $other['data'][2], 'id_module_group' => $other['data'][3], @@ -4040,7 +4357,27 @@ function api_set_create_snmp_module($id, $thrash1, $other, $thrash3) // Column 'descripcion' cannot be null } - $idModule = modules_create_agent_module($idAgent, $name, $values, true); + if ($agent_by_alias) { + $agents_affected = 0; + + foreach ($idsAgents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AW')) { + continue; + } + + $idModule = modules_create_agent_module($id['id_agente'], $name, $values, true); + + if (!is_error($idModule)) { + $agents_affected++; + } + } + + returnData('string', ['type' => 'string', 'data' => $agents_affected.' agents affected']); + + return; + } else { + $idModule = modules_create_agent_module($idAgent, $name, $values, true); + } if (is_error($idModule)) { // TODO: Improve the error returning more info @@ -4743,9 +5080,9 @@ function api_get_module_value_all_agents($id, $thrash1, $other, $thrash2) $sql = sprintf( "SELECT agent.id_agente, agent.alias, module_state.datos, agent.nombre - FROM tagente agent LEFT JOIN tagent_secondary_group tasg ON agent.id_agente = tasg.id_agent, tagente_modulo module, tagente_estado module_state - WHERE agent.id_agente = module.id_agente AND module.id_agente_modulo=module_state.id_agente_modulo AND module.nombre = '%s' - AND %s", + FROM tagente agent LEFT JOIN tagent_secondary_group tasg ON agent.id_agente = tasg.id_agent, tagente_modulo module, tagente_estado module_state + WHERE agent.id_agente = module.id_agente AND module.id_agente_modulo=module_state.id_agente_modulo AND module.nombre = '%s' + AND %s", $id, $groups ); @@ -5372,20 +5709,48 @@ function api_get_plugins($thrash1, $thrash2, $other, $thrash3) * @param $thrash1 Don't use * @param $thrash2 Don't use */ -function api_set_create_network_module_from_component($agent_name, $component_name, $thrash1, $thrash2) +function api_set_create_network_module_from_component($agent_name, $component_name, $other, $thrash2) { if (defined('METACONSOLE')) { return; } - $agent_id = agents_get_agent_id($agent_name); - if (!util_api_check_agent_and_print_error($agent_id, 'string', 'AW')) { - return; + $agent_by_alias = false; + + if ($other['data'][0] === '1') { + $agent_by_alias = true; } - if (!$agent_id) { - returnError('error_network_module_from_component', __('Error creating module from network component. Agent doesn\'t exist.')); - return; + if ($agent_by_alias) { + $ids_agents = agents_get_agent_id_by_alias($agent_name); + } else { + $agent_id = agents_get_agent_id($agent_name); + } + + if ($agent_by_alias) { + foreach ($ids_agents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AW')) { + return; + } + } + } else { + if (!util_api_check_agent_and_print_error($agent_id, 'string', 'AW')) { + return; + } + } + + if ($agent_by_alias) { + foreach ($ids_agents as $id) { + if (!$id['id_agente']) { + returnError('error_network_module_from_component', __('Error creating module from network component. Agent doesn\'t exist.')); + return; + } + } + } else { + if (!$agent_id) { + returnError('error_network_module_from_component', __('Error creating module from network component. Agent doesn\'t exist.')); + return; + } } $component = db_get_row('tnetwork_component', 'name', $component_name); @@ -5406,14 +5771,29 @@ function api_set_create_network_module_from_component($agent_name, $component_na $component['ip_target'] = agents_get_address($agent_id); // Create module - $module_id = modules_create_agent_module($agent_id, $component_name, $component, true); + if ($agent_by_alias) { + $agents_affected = 0; - if (!$module_id) { - returnError('error_network_module_from_component', __('Error creating module from network component. Error creating module.')); + foreach ($ids_agents as $id) { + $module_id = modules_create_agent_module($id['id_agente'], $component_name, $component, true); + + if ($module_id) { + $agents_affected++; + } + } + + returnData('string', ['type' => 'string', 'data' => __('%d agents affected', $agents_affected)]); return; - } + } else { + $module_id = modules_create_agent_module($agent_id, $component_name, $component, true); - return $module_id; + if (!$module_id) { + returnError('error_network_module_from_component', __('Error creating module from network component. Error creating module.')); + return; + } + + return $module_id; + } } @@ -5552,7 +5932,7 @@ function api_set_delete_module_template($id, $thrash1, $other, $thrash3) /** - * Delete an module assigned to a template. And return a message with the result of the operation. + * Delete a module assigned to a template and return a message with the result of the operation. * * @param $id Agent Name * @param $id2 Alert Template Name @@ -5573,11 +5953,6 @@ function api_set_delete_module_template_by_names($id, $id2, $other, $trash1) $result = 0; - if ($other['type'] != 'string') { - returnError('error_parameter', 'Error in the parameters.'); - return; - } - if (! check_acl($config['id_user'], 0, 'AD') && ! check_acl($config['id_user'], 0, 'LM') ) { @@ -5585,10 +5960,26 @@ function api_set_delete_module_template_by_names($id, $id2, $other, $trash1) return; } - $idAgent = agents_get_agent_id($id); + $agent_by_alias = false; - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AD')) { - return; + if ($other['data'][1] === '1') { + $agent_by_alias = true; + } + + if ($agent_by_alias) { + $idsAgents = agents_get_agent_id_by_alias($id); + + foreach ($idsAgents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AD')) { + return; + } + } + } else { + $idAgent = agents_get_agent_id($id); + + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AD')) { + return; + } } $row = db_get_row_filter('talert_templates', ['name' => $id2]); @@ -5601,25 +5992,50 @@ function api_set_delete_module_template_by_names($id, $id2, $other, $trash1) $idTemplate = $row['id']; $idActionTemplate = $row['id_alert_action']; - $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $idAgent, 'nombre' => $other['data']]); + $delete_count = 0; - if ($idAgentModule === false) { - returnError('error_parameter', 'Error in the parameters.'); - return; - } + if ($agent_by_alias) { + foreach ($idsAgents as $id) { + $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id['id_agente'], 'nombre' => $other['data'][0]]); - $values = [ - 'id_agent_module' => $idAgentModule, - 'id_alert_template' => $idTemplate, - ]; + if ($idAgentModule === false) { + continue; + } - $result = db_process_sql_delete('talert_template_modules', $values); + $values = [ + 'id_agent_module' => $idAgentModule, + 'id_alert_template' => $idTemplate, + ]; - if ($result == 0) { - // TODO: Improve the error returning more info - returnError('error_delete_module_template_by_name', __('Error deleting module template.')); + $result = db_process_sql_delete('talert_template_modules', $values); + + if ($result != 0) { + $delete_count++; + } + } + + returnError('error_delete_module_template_by_name', __('Module template has been deleted in %d agents.', $delete_count)); } else { - returnData('string', ['type' => 'string', 'data' => __('Correct deleting of module template.')]); + $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $idAgent, 'nombre' => $other['data'][0]]); + + if ($idAgentModule === false) { + returnError('error_parameter', 'Error in the parameters1.'); + return; + } + + $values = [ + 'id_agent_module' => $idAgentModule, + 'id_alert_template' => $idTemplate, + ]; + + $result = db_process_sql_delete('talert_template_modules', $values); + + if ($result == 0) { + // TODO: Improve the error returning more info + returnError('error_delete_module_template_by_name', __('Error deleting module template.')); + } else { + returnData('string', ['type' => 'string', 'data' => __('Correct deleting of module template.')]); + } } } @@ -5662,15 +6078,15 @@ function api_set_validate_all_alerts($id, $thrash1, $other, $thrash3) $sql = sprintf( ' - SELECT talert_template_modules.id - FROM talert_template_modules - INNER JOIN tagente_modulo t2 - ON talert_template_modules.id_agent_module = t2.id_agente_modulo - INNER JOIN tagente t3 - ON t2.id_agente = t3.id_agente - INNER JOIN talert_templates t4 - ON talert_template_modules.id_alert_template = t4.id - WHERE t3.id_agente in (%s)', + SELECT talert_template_modules.id + FROM talert_template_modules + INNER JOIN tagente_modulo t2 + ON talert_template_modules.id_agent_module = t2.id_agente_modulo + INNER JOIN tagente t3 + ON t2.id_agente = t3.id_agente + INNER JOIN talert_templates t4 + ON talert_template_modules.id_alert_template = t4.id + WHERE t3.id_agente in (%s)', $agents_string ); @@ -5758,9 +6174,9 @@ function api_set_validate_all_policy_alerts($id, $thrash1, $other, $thrash3) if (count($result_pol_alerts) != 0) { $sql = sprintf( ' - SELECT id - FROM talert_template_modules - WHERE id_policy_alerts IN (%s)', + SELECT id + FROM talert_template_modules + WHERE id_policy_alerts IN (%s)', $id_pol_alerts ); @@ -6215,9 +6631,8 @@ function api_set_planned_downtimes_created($id, $thrash1, $other, $thrash3) return; } - $date_from = strtotime(html_entity_decode($other['data'][1])); - $date_to = strtotime(html_entity_decode($other['data'][2])); - + $date_from = strtotime(html_entity_decode($other['data'][1].' '.$other['data'][11])); + $date_to = strtotime(html_entity_decode($other['data'][2].' '.$other['data'][12])); $values = []; $values['name'] = $id; $values = [ @@ -7645,8 +8060,8 @@ function api_set_create_group($id, $thrash1, $other, $thrash3) if (defined('METACONSOLE')) { $servers = db_get_all_rows_sql( 'SELECT * - FROM tmetaconsole_setup - WHERE disabled = 0' + FROM tmetaconsole_setup + WHERE disabled = 0' ); if ($servers === false) { @@ -7935,10 +8350,10 @@ function api_get_module_data($id, $thrash1, $other, $returnType) $sql = sprintf( 'SELECT utimestamp, datos - FROM tagente_datos - WHERE id_agente_modulo = %d AND utimestamp > %d - AND utimestamp < %d - ORDER BY utimestamp DESC', + FROM tagente_datos + WHERE id_agente_modulo = %d AND utimestamp > %d + AND utimestamp < %d + ORDER BY utimestamp DESC', $id, $date_start, $date_end @@ -7947,17 +8362,17 @@ function api_get_module_data($id, $thrash1, $other, $returnType) if ($periodSeconds == null) { $sql = sprintf( 'SELECT utimestamp, datos - FROM tagente_datos - WHERE id_agente_modulo = %d - ORDER BY utimestamp DESC', + FROM tagente_datos + WHERE id_agente_modulo = %d + ORDER BY utimestamp DESC', $id ); } else { $sql = sprintf( 'SELECT utimestamp, datos - FROM tagente_datos - WHERE id_agente_modulo = %d AND utimestamp > %d - ORDER BY utimestamp DESC', + FROM tagente_datos + WHERE id_agente_modulo = %d AND utimestamp > %d + ORDER BY utimestamp DESC', $id, (get_system_time() - $periodSeconds) ); @@ -8276,7 +8691,7 @@ function api_set_enable_disable_user($id, $thrash2, $other, $thrash3) } -function otherParameter2Filter($other, $return_as_array=false) +function otherParameter2Filter($other, $return_as_array=false, $use_agent_name=false) { $filter = []; @@ -8284,14 +8699,28 @@ function otherParameter2Filter($other, $return_as_array=false) $filter['criticity'] = $other['data'][1]; } - $idAgent = null; if (isset($other['data'][2]) && $other['data'][2] != '') { - $idAgents = agents_get_agent_id_by_alias($other['data'][2]); + if ($use_agent_name === false) { + $idAgents = agents_get_agent_id_by_alias($other['data'][2]); - if (!empty($idAgent)) { - $filter[] = 'id_agente IN ('.explode(',', $idAgents).')'; + if (!empty($idAgents)) { + $idAgent = []; + foreach ($idAgents as $key => $value) { + $idAgent[] .= $value['id_agente']; + } + + $filter[] = 'id_agente IN ('.implode(',', $idAgent).')'; + } else { + $filter['sql'] = '1=0'; + } } else { - $filter['sql'] = '1=0'; + $idAgent = agents_get_agent_id($other['data'][2]); + + if (!empty($idAgent)) { + $filter[] = 'id_agente = '.$idAgent; + } else { + $filter['sql'] = '1=0'; + } } } @@ -8302,9 +8731,21 @@ function otherParameter2Filter($other, $return_as_array=false) $filterModule['id_agente'] = $idAgent; } - $idAgentModulo = db_get_value_filter('id_agente_modulo', 'tagente_modulo', $filterModule); - if ($idAgentModulo !== false) { - $filter['id_agentmodule'] = $idAgentModulo; + $idAgentModulo = db_get_all_rows_filter('tagente_modulo', $filterModule, 'id_agente_modulo'); + + if (!empty($idAgentModulo)) { + $id_agentmodule = []; + foreach ($idAgentModulo as $key => $value) { + $id_agentmodule[] .= $value['id_agente_modulo']; + } + + $idAgentModulo = $id_agentmodule; + if ($idAgentModulo !== false) { + $filter['id_agentmodule'] = $idAgentModulo; + } + } else { + // If the module doesn't exist or doesn't exist in that agent. + $filter['sql'] = '1=0'; } } @@ -8393,13 +8834,11 @@ function otherParameter2Filter($other, $return_as_array=false) if ($other['data'][12] == 'more_criticity') { $filter['more_criticity'] = true; } - } else { } } else { if ($return_as_array) { $filter['total'] = false; $filter['more_criticity'] = false; - } else { } } @@ -8407,7 +8846,7 @@ function otherParameter2Filter($other, $return_as_array=false) if ($return_as_array) { $filter['id_group'] = $other['data'][13]; } else { - $filterString .= ' AND id_grupo ='.$other['data'][13]; + $filterString .= ' AND id_grupo = '.$other['data'][13]; } } @@ -8427,7 +8866,7 @@ function otherParameter2Filter($other, $return_as_array=false) if ($event_type == 'not_normal') { $filterString .= " AND ( event_type LIKE '%warning%' - OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%' ) "; + OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%' ) "; } else { $filterString .= ' AND event_type LIKE "%'.$event_type.'%"'; } @@ -8463,48 +8902,91 @@ function api_set_new_alert_template($id, $id2, $other, $trash1) } if ($other['type'] == 'string') { - returnError('error_parameter', 'Error in the parameters.'); + returnError('error_parameter', 'Error in the parameters0.'); return; } else if ($other['type'] == 'array') { - $idAgent = agents_get_agent_id($id); + $agent_by_alias = false; - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { - return; + if ($other['data'][1] === '1') { + $agent_by_alias = true; + } + + if ($agent_by_alias) { + $idsAgents = agents_get_agent_id_by_alias($id); + } else { + $idAgent = agents_get_agent_id($id); + } + + if ($agent_by_alias) { + foreach ($idsAgents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AW')) { + return; + } + } + } else { + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { + return; + } } $row = db_get_row_filter('talert_templates', ['name' => $id2]); if ($row === false) { - returnError('error_parameter', 'Error in the parameters.'); + returnError('error_parameter', 'Error in the parameters1.'); return; } $idTemplate = $row['id']; $idActionTemplate = $row['id_alert_action']; - $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $idAgent, 'nombre' => $other['data'][0]]); + $inserted_count = 0; - if ($idAgentModule === false) { - returnError('error_parameter', 'Error in the parameters.'); + if ($agent_by_alias) { + foreach ($idsAgents as $id) { + $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id['id_agente'], 'nombre' => $other['data'][0]]); + + if ($idAgentModule === false) { + continue; + } + + $values = [ + 'id_agent_module' => $idAgentModule, + 'id_alert_template' => $idTemplate, + ]; + + $return = db_process_sql_insert('talert_template_modules', $values); + + if ($return != false) { + $inserted_count++; + } + } + + returnData('string', ['type' => 'string', 'data' => __('Template have been inserted in %d agents.', $inserted_count)]); + } else { + $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $idAgent, 'nombre' => $other['data'][0]]); + + if ($idAgentModule === false) { + returnError('error_parameter', 'Error in the parameter2s.'); + return; + } + + $values = [ + 'id_agent_module' => $idAgentModule, + 'id_alert_template' => $idTemplate, + ]; + + $return = db_process_sql_insert('talert_template_modules', $values); + + $data['type'] = 'string'; + if ($return === false) { + $data['data'] = 0; + } else { + $data['data'] = $return; + } + + returnData('string', $data); return; } - - $values = [ - 'id_agent_module' => $idAgentModule, - 'id_alert_template' => $idTemplate, - ]; - - $return = db_process_sql_insert('talert_template_modules', $values); - - $data['type'] = 'string'; - if ($return === false) { - $data['data'] = 0; - } else { - $data['data'] = $return; - } - - returnData('string', $data); - return; } } @@ -8515,18 +8997,61 @@ function api_set_delete_module($id, $id2, $other, $trash1) return; } - if ($other['type'] == 'string') { - $simulate = false; - if ($other['data'] == 'simulate') { - $simulate = true; - } + $simulate = false; + if ($other['data'][0] == 'simulate') { + $simulate = true; + } + $agent_by_alias = false; + + if ($other['data'][1] === '1') { + $agent_by_alias = true; + } + + if ($agent_by_alias) { + $idsAgents = agents_get_agent_id_by_alias($id); + } else { $idAgent = agents_get_agent_id($id); + } + if ($agent_by_alias) { + foreach ($idsAgents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AD')) { + return; + } + } + } else { if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AD')) { return; } + } + if ($agent_by_alias) { + foreach ($idsAgents as $id) { + $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id['id_agente'], 'nombre' => $id2]); + + if ($idAgentModule === false) { + continue; + } + + if (!$simulate) { + $return = modules_delete_agent_module($idAgentModule); + } else { + $return = true; + } + + $data['type'] = 'string'; + if ($return === false) { + $data['data'] = 0; + } else { + $data['data'] = $return; + } + + returnData('string', $data); + } + + return; + } else { $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $idAgent, 'nombre' => $id2]); if ($idAgentModule === false) { @@ -8549,9 +9074,6 @@ function api_set_delete_module($id, $id2, $other, $trash1) returnData('string', $data); return; - } else { - returnError('error_parameter', 'Error in the parameters.'); - return; } } @@ -8582,14 +9104,14 @@ function api_set_module_data($id, $thrash2, $other, $trash1) $agent = db_get_row_filter('tagente', ['id_agente' => $agentModule['id_agente']]); $xmlTemplate = " - - - - - - - - "; + + + + + + + + "; $xml = sprintf( $xmlTemplate, @@ -8631,9 +9153,29 @@ function api_set_new_module($id, $id2, $other, $trash1) return; } else if ($other['type'] == 'array') { $values = []; - $values['id_agente'] = agents_get_agent_id($id); - if (!util_api_check_agent_and_print_error($values['id_agente'], 'string', 'AW')) { - return; + + $agent_by_alias = false; + + if ($other['data'][15] === '1') { + $agent_by_alias = true; + } + + if ($agent_by_alias) { + $idsAgents = agents_get_agent_id_by_alias($id); + } else { + $values['id_agente'] = agents_get_agent_id($id); + } + + if ($agent_by_alias) { + foreach ($idsAgents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AW')) { + return; + } + } + } else { + if (!util_api_check_agent_and_print_error($values['id_agente'], 'string', 'AW')) { + return; + } } $values['nombre'] = $id2; @@ -8713,11 +9255,30 @@ function api_set_new_module($id, $id2, $other, $trash1) $values['id_modulo'] = 2; - $return = modules_create_agent_module( - $values['id_agente'], - $values['nombre'], - $values - ); + if ($agent_by_alias) { + $agents_module_created = 0; + + foreach ($idsAgents as $id) { + $return = modules_create_agent_module( + $id['id_agente'], + $values['nombre'], + $values + ); + + if ($return != false) { + $agents_module_created++; + } + } + + returnData('string', ['type' => 'string', 'data' => __('Module has been created in %d agents.', $agents_module_created)]); + return; + } else { + $return = modules_create_agent_module( + $values['id_agente'], + $values['nombre'], + $values + ); + } $data['type'] = 'string'; if ($return === false) { @@ -8753,66 +9314,133 @@ function api_set_alert_actions($id, $id2, $other, $trash1) } if ($other['type'] == 'string') { - returnError('error_parameter', 'Error in the parameters.'); + returnError('error_parameter', 'Error in the parameters0.'); return; } else if ($other['type'] == 'array') { - $idAgent = agents_get_agent_id($id); - if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { - return; + $agent_by_alias = false; + + if ($other['data'][4] === '1') { + $agent_by_alias = true; + } + + if ($agent_by_alias) { + $idsAgents = agents_get_agent_id_by_alias($id); + } else { + $idAgent = agents_get_agent_id($id); + } + + if ($agent_by_alias) { + foreach ($idsAgents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AW')) { + return; + } + } + } else { + if (!util_api_check_agent_and_print_error($idAgent, 'string', 'AW')) { + return; + } } $row = db_get_row_filter('talert_templates', ['name' => $id2]); if ($row === false) { - returnError('error_parameter', 'Error in the parameters.'); + returnError('error_parameter', 'Error in the parameters1.'); return; } $idTemplate = $row['id']; - $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $idAgent, 'nombre' => $other['data'][0]]); - if ($idAgentModule === false) { - returnError('error_parameter', 'Error in the parameters.'); - return; - } + if ($agent_by_alias) { + $actions_set = 0; - $idAlertTemplateModule = db_get_value_filter('id', 'talert_template_modules', ['id_alert_template' => $idTemplate, 'id_agent_module' => $idAgentModule]); - if ($idAlertTemplateModule === false) { - returnError('error_parameter', 'Error in the parameters.'); - return; - } + foreach ($idsAgents as $id) { + $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id['id_agente'], 'nombre' => $other['data'][0]]); + if ($idAgentModule === false) { + continue; + } - if ($other['data'][1] != '') { - $idAction = db_get_value_filter('id', 'talert_actions', ['name' => $other['data'][1]]); - if ($idAction === false) { + $idAlertTemplateModule = db_get_value_filter('id', 'talert_template_modules', ['id_alert_template' => $idTemplate, 'id_agent_module' => $idAgentModule]); + if ($idAlertTemplateModule === false) { + returnError('error_parameter', 'Error in the parameters.'); + return; + } + + if ($other['data'][1] != '') { + $idAction = db_get_value_filter('id', 'talert_actions', ['name' => $other['data'][1]]); + if ($idAction === false) { + returnError('error_parameter', 'Error in the parameters.'); + return; + } + } else { + returnError('error_parameter', 'Error in the parameters.'); + return; + } + + $firesMin = $other['data'][2]; + $firesMax = $other['data'][3]; + + $values = [ + 'id_alert_template_module' => $idAlertTemplateModule, + 'id_alert_action' => $idAction, + 'fires_min' => $firesMin, + 'fires_max' => $firesMax, + ]; + + $return = db_process_sql_insert('talert_template_module_actions', $values); + + if ($return != false) { + $actions_set++; + } + } + + returnData('string', ['type' => 'string', 'data' => __('Action has been set for %d agents.', $actions_set)]); + + return; + } else { + $idAgentModule = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $idAgent, 'nombre' => $other['data'][0]]); + if ($idAgentModule === false) { returnError('error_parameter', 'Error in the parameters.'); return; } - } else { - returnError('error_parameter', 'Error in the parameters.'); + + $idAlertTemplateModule = db_get_value_filter('id', 'talert_template_modules', ['id_alert_template' => $idTemplate, 'id_agent_module' => $idAgentModule]); + if ($idAlertTemplateModule === false) { + returnError('error_parameter', 'Error in the parameters.'); + return; + } + + if ($other['data'][1] != '') { + $idAction = db_get_value_filter('id', 'talert_actions', ['name' => $other['data'][1]]); + if ($idAction === false) { + returnError('error_parameter', 'Error in the parameters.'); + return; + } + } else { + returnError('error_parameter', 'Error in the parameters.'); + return; + } + + $firesMin = $other['data'][2]; + $firesMax = $other['data'][3]; + + $values = [ + 'id_alert_template_module' => $idAlertTemplateModule, + 'id_alert_action' => $idAction, + 'fires_min' => $firesMin, + 'fires_max' => $firesMax, + ]; + + $return = db_process_sql_insert('talert_template_module_actions', $values); + + $data['type'] = 'string'; + if ($return === false) { + $data['data'] = 0; + } else { + $data['data'] = $return; + } + + returnData('string', $data); return; } - - $firesMin = $other['data'][2]; - $firesMax = $other['data'][3]; - - $values = [ - 'id_alert_template_module' => $idAlertTemplateModule, - 'id_alert_action' => $idAction, - 'fires_min' => $firesMin, - 'fires_max' => $firesMax, - ]; - - $return = db_process_sql_insert('talert_template_module_actions', $values); - - $data['type'] = 'string'; - if ($return === false) { - $data['data'] = 0; - } else { - $data['data'] = $return; - } - - returnData('string', $data); - return; } } @@ -9141,11 +9769,11 @@ function api_set_new_event($trash1, $trash2, $other, $trash3) } else { $idAlert = db_get_value_sql( "SELECT t1.id - FROM talert_template_modules t1 - INNER JOIN talert_templates t2 - ON t1.id_alert_template = t2.id - WHERE t1.id_agent_module = 1 - AND t2.name LIKE '".$other['data'][7]."'" + FROM talert_template_modules t1 + INNER JOIN talert_templates t2 + ON t1.id_alert_template = t2.id + WHERE t1.id_agent_module = 1 + AND t2.name LIKE '".$other['data'][7]."'" ); if ($idAlert === false) { @@ -9299,7 +9927,9 @@ function api_set_event_validate_filter($trash1, $trash2, $other, $trash3) } } - $filterString = otherParameter2Filter($other); + $use_agent_name = ($other['data'][8] === '1') ? true : false; + + $filterString = otherParameter2Filter($other, false, $use_agent_name); if (!users_can_manage_group_all('EW')) { $user_groups = implode( @@ -9382,9 +10012,9 @@ function api_get_gis_agent($id_agent, $trash1, $tresh2, $return_type, $user_in_d $agent_gis_data = db_get_row_sql( ' - SELECT * - FROM tgis_data_status - WHERE tagente_id_agente = '.$id_agent + SELECT * + FROM tgis_data_status + WHERE tagente_id_agente = '.$id_agent ); if ($agent_gis_data) { @@ -9616,7 +10246,9 @@ function get_events_with_user($trash1, $trash2, $other, $returnType, $user_in_db $utimestamp_upper = 0; $utimestamp_bottom = 0; - $filter = otherParameter2Filter($other, true); + $use_agent_name = ($other['data'][16] === '1') ? true : false; + + $filter = otherParameter2Filter($other, true, $use_agent_name); if (isset($filter['criticity'])) { $severity = $filter['criticity']; @@ -9751,7 +10383,7 @@ function get_events_with_user($trash1, $trash2, $other, $returnType, $user_in_db $sql_post .= " AND event_type LIKE '%$event_type%' "; } else if ($event_type == 'not_normal') { $sql_post .= " AND ( event_type LIKE '%warning%' - OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%' ) "; + OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%' ) "; } else { $sql_post .= " AND event_type = '".$event_type."'"; } @@ -9810,48 +10442,48 @@ function get_events_with_user($trash1, $trash2, $other, $returnType, $user_in_db case 'mysql': if ($filter['total']) { $sql = 'SELECT COUNT(*) - FROM '.$table_events.' - WHERE 1=1 '.$sql_post; + FROM '.$table_events.' + WHERE 1=1 '.$sql_post; } else if ($filter['more_criticity']) { $sql = 'SELECT criticity - FROM '.$table_events.' - WHERE 1=1 '.$sql_post.' - ORDER BY criticity DESC - LIMIT 1'; + FROM '.$table_events.' + WHERE 1=1 '.$sql_post.' + ORDER BY criticity DESC + LIMIT 1'; } else { if (defined('METACONSOLE')) { $sql = 'SELECT *, - (SELECT t2.nombre - FROM tgrupo t2 - WHERE t2.id_grupo = '.$table_events.'.id_grupo) AS group_name, - (SELECT t2.icon - FROM tgrupo t2 - WHERE t2.id_grupo = '.$table_events.'.id_grupo) AS group_icon - FROM '.$table_events.' - WHERE 1=1 '.$sql_post.' - ORDER BY utimestamp DESC - LIMIT '.$offset.','.$pagination; + (SELECT t2.nombre + FROM tgrupo t2 + WHERE t2.id_grupo = '.$table_events.'.id_grupo) AS group_name, + (SELECT t2.icon + FROM tgrupo t2 + WHERE t2.id_grupo = '.$table_events.'.id_grupo) AS group_icon + FROM '.$table_events.' + WHERE 1=1 '.$sql_post.' + ORDER BY utimestamp DESC + LIMIT '.$offset.','.$pagination; } else { $sql = 'SELECT *, - (SELECT t1.alias - FROM tagente t1 - WHERE t1.id_agente = tevento.id_agente) AS agent_name, - (SELECT t2.nombre - FROM tgrupo t2 - WHERE t2.id_grupo = tevento.id_grupo) AS group_name, - (SELECT t2.icon - FROM tgrupo t2 - WHERE t2.id_grupo = tevento.id_grupo) AS group_icon, - (SELECT tmodule.name - FROM tmodule - WHERE id_module IN ( - SELECT tagente_modulo.id_modulo - FROM tagente_modulo - WHERE tagente_modulo.id_agente_modulo=tevento.id_agentmodule)) AS module_name - FROM '.$table_events.' - WHERE 1=1 '.$sql_post.' - ORDER BY utimestamp DESC - LIMIT '.$offset.','.$pagination; + (SELECT t1.alias + FROM tagente t1 + WHERE t1.id_agente = tevento.id_agente) AS agent_name, + (SELECT t2.nombre + FROM tgrupo t2 + WHERE t2.id_grupo = tevento.id_grupo) AS group_name, + (SELECT t2.icon + FROM tgrupo t2 + WHERE t2.id_grupo = tevento.id_grupo) AS group_icon, + (SELECT tmodule.name + FROM tmodule + WHERE id_module IN ( + SELECT tagente_modulo.id_modulo + FROM tagente_modulo + WHERE tagente_modulo.id_agente_modulo=tevento.id_agentmodule)) AS module_name + FROM '.$table_events.' + WHERE 1=1 '.$sql_post.' + ORDER BY utimestamp DESC + LIMIT '.$offset.','.$pagination; } } break; @@ -9859,25 +10491,25 @@ function get_events_with_user($trash1, $trash2, $other, $returnType, $user_in_db case 'postgresql': // TODO TOTAL $sql = 'SELECT *, - (SELECT t1.alias - FROM tagente t1 - WHERE t1.id_agente = tevento.id_agente) AS agent_name, - (SELECT t2.nombre - FROM tgrupo t2 - WHERE t2.id_grupo = tevento.id_grupo) AS group_name, - (SELECT t2.icon - FROM tgrupo t2 - WHERE t2.id_grupo = tevento.id_grupo) AS group_icon, - (SELECT tmodule.name - FROM tmodule - WHERE id_module IN ( - SELECT tagente_modulo.id_modulo - FROM tagente_modulo - WHERE tagente_modulo.id_agente_modulo=tevento.id_agentmodule)) AS module_name - FROM tevento - WHERE 1=1 '.$sql_post.' - ORDER BY utimestamp DESC - LIMIT '.$pagination.' OFFSET '.$offset; + (SELECT t1.alias + FROM tagente t1 + WHERE t1.id_agente = tevento.id_agente) AS agent_name, + (SELECT t2.nombre + FROM tgrupo t2 + WHERE t2.id_grupo = tevento.id_grupo) AS group_name, + (SELECT t2.icon + FROM tgrupo t2 + WHERE t2.id_grupo = tevento.id_grupo) AS group_icon, + (SELECT tmodule.name + FROM tmodule + WHERE id_module IN ( + SELECT tagente_modulo.id_modulo + FROM tagente_modulo + WHERE tagente_modulo.id_agente_modulo=tevento.id_agentmodule)) AS module_name + FROM tevento + WHERE 1=1 '.$sql_post.' + ORDER BY utimestamp DESC + LIMIT '.$pagination.' OFFSET '.$offset; break; case 'oracle': @@ -9887,26 +10519,26 @@ function get_events_with_user($trash1, $trash2, $other, $returnType, $user_in_db $set['offset'] = $offset; $sql = 'SELECT *, - (SELECT t1.alias - FROM tagente t1 - WHERE t1.id_agente = tevento.id_agente) AS alias, - (SELECT t1.nombre - FROM tagente t1 - WHERE t1.id_agente = tevento.id_agente) AS agent_name, - (SELECT t2.nombre - FROM tgrupo t2 - WHERE t2.id_grupo = tevento.id_grupo) AS group_name, - (SELECT t2.icon - FROM tgrupo t2 - WHERE t2.id_grupo = tevento.id_grupo) AS group_icon, - (SELECT tmodule.name - FROM tmodule - WHERE id_module IN ( - SELECT tagente_modulo.id_modulo - FROM tagente_modulo - WHERE tagente_modulo.id_agente_modulo=tevento.id_agentmodule)) AS module_name - FROM tevento - WHERE 1=1 '.$sql_post.' ORDER BY utimestamp DESC'; + (SELECT t1.alias + FROM tagente t1 + WHERE t1.id_agente = tevento.id_agente) AS alias, + (SELECT t1.nombre + FROM tagente t1 + WHERE t1.id_agente = tevento.id_agente) AS agent_name, + (SELECT t2.nombre + FROM tgrupo t2 + WHERE t2.id_grupo = tevento.id_grupo) AS group_name, + (SELECT t2.icon + FROM tgrupo t2 + WHERE t2.id_grupo = tevento.id_grupo) AS group_icon, + (SELECT tmodule.name + FROM tmodule + WHERE id_module IN ( + SELECT tagente_modulo.id_modulo + FROM tagente_modulo + WHERE tagente_modulo.id_agente_modulo=tevento.id_agentmodule)) AS module_name + FROM tevento + WHERE 1=1 '.$sql_post.' ORDER BY utimestamp DESC'; $sql = oracle_recode_query($sql, $set); break; } @@ -9916,26 +10548,26 @@ function get_events_with_user($trash1, $trash2, $other, $returnType, $user_in_db db_process_sql('SET group_concat_max_len = 9999999'); $sql = "SELECT *, MAX(id_evento) AS id_evento, - GROUP_CONCAT(DISTINCT user_comment SEPARATOR '') AS user_comment, - MIN(estado) AS min_estado, MAX(estado) AS max_estado, - COUNT(*) AS event_rep, MAX(utimestamp) AS timestamp_rep - FROM ".$table_events.' - WHERE 1=1 '.$sql_post.' - GROUP BY evento, id_agentmodule - ORDER BY timestamp_rep DESC - LIMIT '.$offset.','.$pagination; + GROUP_CONCAT(DISTINCT user_comment SEPARATOR '') AS user_comment, + MIN(estado) AS min_estado, MAX(estado) AS max_estado, + COUNT(*) AS event_rep, MAX(utimestamp) AS timestamp_rep + FROM ".$table_events.' + WHERE 1=1 '.$sql_post.' + GROUP BY evento, id_agentmodule + ORDER BY timestamp_rep DESC + LIMIT '.$offset.','.$pagination; break; case 'postgresql': $sql = "SELECT *, MAX(id_evento) AS id_evento, - array_to_string(array_agg(DISTINCT user_comment), '') AS user_comment, - MIN(estado) AS min_estado, MAX(estado) AS max_estado, - COUNT(*) AS event_rep, MAX(utimestamp) AS timestamp_rep - FROM ".$table_events.' - WHERE 1=1 '.$sql_post.' - GROUP BY evento, id_agentmodule - ORDER BY timestamp_rep DESC - LIMIT '.$pagination.' OFFSET '.$offset; + array_to_string(array_agg(DISTINCT user_comment), '') AS user_comment, + MIN(estado) AS min_estado, MAX(estado) AS max_estado, + COUNT(*) AS event_rep, MAX(utimestamp) AS timestamp_rep + FROM ".$table_events.' + WHERE 1=1 '.$sql_post.' + GROUP BY evento, id_agentmodule + ORDER BY timestamp_rep DESC + LIMIT '.$pagination.' OFFSET '.$offset; break; case 'oracle': @@ -9944,21 +10576,21 @@ function get_events_with_user($trash1, $trash2, $other, $returnType, $user_in_db $set['offset'] = $offset; // TODO: Remove duplicate user comments $sql = 'SELECT a.*, b.event_rep, b.timestamp_rep - FROM (SELECT * - FROM tevento - WHERE 1=1 '.$sql_post.") a, - (SELECT MAX (id_evento) AS id_evento, - to_char(evento) AS evento, id_agentmodule, - COUNT(*) AS event_rep, MIN(estado) AS min_estado, - MAX(estado) AS max_estado, - LISTAGG(user_comment, '') AS user_comment, - MAX(utimestamp) AS timestamp_rep - FROM ".$table_events.' - WHERE 1=1 '.$sql_post.' - GROUP BY to_char(evento), id_agentmodule) b - WHERE a.id_evento=b.id_evento AND - to_char(a.evento)=to_char(b.evento) AND - a.id_agentmodule=b.id_agentmodule'; + FROM (SELECT * + FROM tevento + WHERE 1=1 '.$sql_post.") a, + (SELECT MAX (id_evento) AS id_evento, + to_char(evento) AS evento, id_agentmodule, + COUNT(*) AS event_rep, MIN(estado) AS min_estado, + MAX(estado) AS max_estado, + LISTAGG(user_comment, '') AS user_comment, + MAX(utimestamp) AS timestamp_rep + FROM ".$table_events.' + WHERE 1=1 '.$sql_post.' + GROUP BY to_char(evento), id_agentmodule) b + WHERE a.id_evento=b.id_evento AND + to_char(a.evento)=to_char(b.evento) AND + a.id_agentmodule=b.id_agentmodule'; $sql = oracle_recode_query($sql, $set); break; } @@ -10036,8 +10668,7 @@ function get_events_with_user($trash1, $trash2, $other, $returnType, $user_in_db $data['type'] = 'array'; $data['data'] = $result; - returnData($returnType, $data, $separator); - + // returnData($returnType, $data, $separator); if (empty($result)) { return false; } @@ -10077,8 +10708,6 @@ function api_get_events($trash1, $trash2, $other, $returnType, $user_in_db=null) returnError('ERROR_API_PANDORAFMS', $returnType); } } - - return; } if ($other['type'] == 'string') { @@ -10092,10 +10721,13 @@ function api_get_events($trash1, $trash2, $other, $returnType, $user_in_db=null) } else if ($other['type'] == 'array') { $separator = $other['data'][0]; - $filterString = otherParameter2Filter($other); + // By default it uses agent alias. + $use_agent_name = ($other['data'][16] === '1') ? true : false; + + $filterString = otherParameter2Filter($other, false, $use_agent_name); } - if (defined('METACONSOLE')) { + if (is_metaconsole()) { $dataRows = db_get_all_rows_filter('tmetaconsole_event', $filterString); } else { $dataRows = db_get_all_rows_filter('tevento', $filterString); @@ -10576,25 +11208,58 @@ function api_set_new_note_incident($id, $id2, $other, $thrash2) */ -function api_set_disable_module($agent_name, $module_name, $thrast3, $thrash4) +function api_set_disable_module($agent_name, $module_name, $other, $thrash4) { if (defined('METACONSOLE')) { return; } - $id_agent = agents_get_agent_id($agent_name); - if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AD')) { - return; + $agent_by_alias = false; + + if ($other['data'][0] === '1') { + $agent_by_alias = true; } - $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id_agent, 'nombre' => $module_name]); + if ($agent_by_alias) { + $ids_agents = agents_get_agent_id_by_alias($agent_name); - $result = modules_change_disabled($id_agent_module, 1); - - if ($result === NOERR) { - returnData('string', ['type' => 'string', 'data' => __('Correct module disable')]); + foreach ($ids_agents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AD')) { + return; + } + } } else { - returnData('string', ['type' => 'string', 'data' => __('Error disabling module')]); + $id_agent = agents_get_agent_id($agent_name); + + if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AD')) { + return; + } + } + + if ($agent_by_alias) { + $agents_affected = 0; + + foreach ($ids_agents as $id) { + $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id['id_agente'], 'nombre' => $module_name]); + + $result = modules_change_disabled($id_agent_module, 1); + + if ($result === NOERR) { + $agents_affected++; + } + } + + returnData('string', ['type' => 'string', 'data' => __('%d agents affected', $agents_affected)]); + } else { + $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id_agent, 'nombre' => $module_name]); + + $result = modules_change_disabled($id_agent_module, 1); + + if ($result === NOERR) { + returnData('string', ['type' => 'string', 'data' => __('Correct module disable')]); + } else { + returnData('string', ['type' => 'string', 'data' => __('Error disabling module')]); + } } } @@ -10609,25 +11274,58 @@ function api_set_disable_module($agent_name, $module_name, $thrast3, $thrash4) */ -function api_set_enable_module($agent_name, $module_name, $thrast3, $thrash4) +function api_set_enable_module($agent_name, $module_name, $other, $thrash4) { if (defined('METACONSOLE')) { return; } - $id_agent = agents_get_agent_id($agent_name); - if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AD')) { - return; + $agent_by_alias = false; + + if ($other['data'][0] === '1') { + $agent_by_alias = true; } - $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id_agent, 'nombre' => $module_name]); + if ($agent_by_alias) { + $ids_agents = agents_get_agent_id_by_alias($agent_name); - $result = modules_change_disabled($id_agent_module, 0); - - if ($result === NOERR) { - returnData('string', ['type' => 'string', 'data' => __('Correct module enable')]); + foreach ($ids_agents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AD')) { + return; + } + } } else { - returnData('string', ['type' => 'string', 'data' => __('Error enabling module')]); + $id_agent = agents_get_agent_id($agent_name); + + if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AD')) { + return; + } + } + + if ($agent_by_alias) { + $agents_affected = 0; + + foreach ($ids_agents as $id) { + $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id['id_agente'], 'nombre' => $module_name]); + + $result = modules_change_disabled($id_agent_module, 0); + + if ($result === NOERR) { + $agents_affected++; + } + } + + returnData('string', ['type' => 'string', 'data' => __('%d agents affected', $agents_affected)]); + } else { + $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id_agent, 'nombre' => $module_name]); + + $result = modules_change_disabled($id_agent_module, 0); + + if ($result === NOERR) { + returnData('string', ['type' => 'string', 'data' => __('Correct module enable')]); + } else { + returnData('string', ['type' => 'string', 'data' => __('Error enabling module')]); + } } } @@ -10667,8 +11365,8 @@ function api_set_disable_alert($agent_name, $module_name, $template_name, $thras $result = db_process_sql( "UPDATE talert_template_modules - SET disabled = 1 - WHERE id_agent_module = $id_agent_module AND id_alert_template = $id_template" + SET disabled = 1 + WHERE id_agent_module = $id_agent_module AND id_alert_template = $id_template" ); if ($result) { @@ -10716,8 +11414,8 @@ function api_set_disable_alert_alias($agent_alias, $module_name, $template_name, $result = db_process_sql( "UPDATE talert_template_modules - SET disabled = 1 - WHERE id_agent_module = $id_agent_module AND id_alert_template = $id_template" + SET disabled = 1 + WHERE id_agent_module = $id_agent_module AND id_alert_template = $id_template" ); if ($result) { @@ -10767,8 +11465,8 @@ function api_set_enable_alert($agent_name, $module_name, $template_name, $thrash $result = db_process_sql( "UPDATE talert_template_modules - SET disabled = 0 - WHERE id_agent_module = $id_agent_module AND id_alert_template = $id_template" + SET disabled = 0 + WHERE id_agent_module = $id_agent_module AND id_alert_template = $id_template" ); if ($result) { @@ -10816,8 +11514,8 @@ function api_set_enable_alert_alias($agent_alias, $module_name, $template_name, $result = db_process_sql( "UPDATE talert_template_modules - SET disabled = 0 - WHERE id_agent_module = $id_agent_module AND id_alert_template = $id_template" + SET disabled = 0 + WHERE id_agent_module = $id_agent_module AND id_alert_template = $id_template" ); if ($result) { @@ -10844,7 +11542,7 @@ function api_set_enable_alert_alias($agent_alias, $module_name, $template_name, */ -function api_set_disable_module_alerts($agent_name, $module_name, $thrash3, $thrash4) +function api_set_disable_module_alerts($agent_name, $module_name, $other, $thrash4) { global $config; @@ -10857,20 +11555,59 @@ function api_set_disable_module_alerts($agent_name, $module_name, $thrash3, $thr return; } - $id_agent = agents_get_agent_id($agent_name); - if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AW')) { - return; + $agent_by_alias = false; + + if ($other['data'][0] === '1') { + $agent_by_alias = true; } - $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id_agent, 'nombre' => $module_name]); + if ($agent_by_alias) { + $ids_agents = agents_get_agent_id_by_alias($agent_name); + } else { + $id_agent = agents_get_agent_id($agent_name); + } - db_process_sql( - "UPDATE talert_template_modules - SET disabled = 1 - WHERE id_agent_module = $id_agent_module" - ); + if ($agent_by_alias) { + foreach ($ids_agents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AW')) { + return; + } + } + } else { + if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AW')) { + return; + } + } - returnData('string', ['type' => 'string', 'data' => 'Correct alerts disable']); + if ($agent_by_alias) { + $agents_affected = 0; + + foreach ($ids_agents as $id) { + $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id['id_agente'], 'nombre' => $module_name]); + + $return_value = db_process_sql( + "UPDATE talert_template_modules + SET disabled = 1 + WHERE id_agent_module = $id_agent_module" + ); + + if ($return_value != false) { + $agents_affected++; + } + } + + returnData('string', ['type' => 'string', 'data' => __('%d agents affected', $agents_affected)]); + } else { + $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id_agent, 'nombre' => $module_name]); + + db_process_sql( + "UPDATE talert_template_modules + SET disabled = 1 + WHERE id_agent_module = $id_agent_module" + ); + + returnData('string', ['type' => 'string', 'data' => 'Correct alerts disable']); + } } @@ -10886,7 +11623,7 @@ function api_set_disable_module_alerts($agent_name, $module_name, $thrash3, $thr */ -function api_set_enable_module_alerts($agent_name, $module_name, $thrash3, $thrash4) +function api_set_enable_module_alerts($agent_name, $module_name, $other, $thrash4) { global $config; @@ -10899,20 +11636,59 @@ function api_set_enable_module_alerts($agent_name, $module_name, $thrash3, $thra return; } - $id_agent = agents_get_agent_id($agent_name); - if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AW')) { - return; + $agent_by_alias = false; + + if ($other['data'][0] === '1') { + $agent_by_alias = true; } - $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id_agent, 'nombre' => $module_name]); + if ($agent_by_alias) { + $ids_agents = agents_get_agent_id_by_alias($agent_name); + } else { + $id_agent = agents_get_agent_id($agent_name); + } - db_process_sql( - "UPDATE talert_template_modules - SET disabled = 0 - WHERE id_agent_module = $id_agent_module" - ); + if ($agent_by_alias) { + foreach ($ids_agents as $id) { + if (!util_api_check_agent_and_print_error($id['id_agente'], 'string', 'AW')) { + return; + } + } + } else { + if (!util_api_check_agent_and_print_error($id_agent, 'string', 'AW')) { + return; + } + } - returnData('string', ['type' => 'string', 'data' => 'Correct alerts enable']); + if ($agent_by_alias) { + $agents_affected = 0; + + foreach ($ids_agents as $id) { + $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id['id_agente'], 'nombre' => $module_name]); + + $return_value = db_process_sql( + "UPDATE talert_template_modules + SET disabled = 0 + WHERE id_agent_module = $id_agent_module" + ); + + if ($return_value != false) { + $agents_affected++; + } + } + + returnData('string', ['type' => 'string', 'data' => __('%d agents affected', $agents_affected)]); + } else { + $id_agent_module = db_get_value_filter('id_agente_modulo', 'tagente_modulo', ['id_agente' => $id_agent, 'nombre' => $module_name]); + + db_process_sql( + "UPDATE talert_template_modules + SET disabled = 0 + WHERE id_agent_module = $id_agent_module" + ); + + returnData('string', ['type' => 'string', 'data' => 'Correct alerts enable']); + } } @@ -10984,11 +11760,11 @@ function api_get_total_modules($id_group, $trash1, $trash2, $returnType) } $sql = "SELECT COUNT(DISTINCT(id_agente_modulo)) - FROM tagente_modulo tam, tagente ta - LEFT JOIN tagent_secondary_group tasg - ON ta.id_agente = tasg.id_agent - WHERE tam.id_agente = ta.id_agente AND id_module_group = $id_group - AND delete_pending = 0 AND $groups_clause"; + FROM tagente_modulo tam, tagente ta + LEFT JOIN tagent_secondary_group tasg + ON ta.id_agente = tasg.id_agent + WHERE tam.id_agente = ta.id_agente AND id_module_group = $id_group + AND delete_pending = 0 AND $groups_clause"; $total = db_get_value_sql($sql); @@ -11049,8 +11825,8 @@ function api_get_agent_name($id_agent, $trash1, $trash2, $returnType) $sql = sprintf( 'SELECT nombre - FROM tagente - WHERE id_agente = %d', + FROM tagente + WHERE id_agente = %d', $id_agent ); $value = db_get_value_sql($sql); @@ -11126,8 +11902,8 @@ function api_get_agent_alias($id_agent, $id_node, $trash1, $returnType) $sql = sprintf( 'SELECT alias - FROM '.$table_agent_alias.' - WHERE id_agente = %d', + FROM '.$table_agent_alias.' + WHERE id_agente = %d', $id_agent ); $value = db_get_value_sql($sql); @@ -11159,8 +11935,8 @@ function api_get_module_name($id_module, $trash1, $trash2, $returnType) $sql = sprintf( 'SELECT nombre - FROM tagente_modulo - WHERE id_agente_modulo = %d', + FROM tagente_modulo + WHERE id_agente_modulo = %d', $id_module ); @@ -11201,15 +11977,15 @@ function api_get_alert_action_by_group($id_group, $id_action, $trash2, $returnTy } $sql = "SELECT SUM(internal_counter) - FROM - talert_template_modules tatm, - tagente ta LEFT JOIN tagent_secondary_group tasg - ON ta.id_agente = tasg.id_agent, - tagente_modulo tam - WHERE tam.id_agente = ta.id_agente - AND tatm.id_agent_module = tam.id_agente_modulo - AND ta.disabled = 0 - AND $filter_groups"; + FROM + talert_template_modules tatm, + tagente ta LEFT JOIN tagent_secondary_group tasg + ON ta.id_agente = tasg.id_agent, + tagente_modulo tam + WHERE tam.id_agente = ta.id_agente + AND tatm.id_agent_module = tam.id_agente_modulo + AND ta.disabled = 0 + AND $filter_groups"; $value = db_get_value_sql($sql); @@ -11239,8 +12015,8 @@ function api_get_event_info($id_event, $trash1, $trash, $returnType) } $sql = 'SELECT * - FROM '.$table_events." - WHERE id_evento=$id_event"; + FROM '.$table_events." + WHERE id_evento=$id_event"; $event_data = db_get_row_sql($sql); // Check the access to group @@ -13768,8 +14544,8 @@ function api_set_create_event_filter($name, $thrash1, $other, $thrash3) } else { $sql = sprintf( 'SELECT alias - FROM tagente - WHERE id_agente = %d', + FROM tagente + WHERE id_agente = %d', $agent[0]['id_agente'] ); @@ -13812,8 +14588,8 @@ function api_set_create_event_filter($name, $thrash1, $other, $thrash3) $agents = db_get_all_rows_sql( 'SELECT id_agente - FROM tagente - WHERE id_grupo IN ('.$id_groups.')' + FROM tagente + WHERE id_grupo IN ('.$id_groups.')' ); if ($agents === false) { @@ -13982,8 +14758,8 @@ function api_set_update_event_filter($id_event_filter, $thrash1, $other, $thrash } else { $sql = sprintf( 'SELECT alias - FROM tagente - WHERE id_agente = %d', + FROM tagente + WHERE id_agente = %d', $agent[0]['id_agente'] ); @@ -14025,12 +14801,10 @@ function api_set_update_event_filter($id_event_filter, $thrash1, $other, $thrash break; case 14: - print_r('14444444'); $values['tag_with'] = (preg_match('/^\[(("\d+"((,|\])("\d+"))+)|"\d+")\]$/', io_safe_output($other['data'][14]))) ? $other['data'][14] : '[]'; break; case 15: - print_r('1555555555'); $values['tag_without'] = (preg_match('/^\[(("\d+"((,|\])("\d+"))+)|"\d+")\]$/', io_safe_output($other['data'][15]))) ? $other['data'][15] : '[]'; break; @@ -14055,8 +14829,8 @@ function api_set_update_event_filter($id_event_filter, $thrash1, $other, $thrash $agents = db_get_all_rows_sql( 'SELECT id_agente - FROM tagente - WHERE id_grupo IN ('.$id_groups.')' + FROM tagente + WHERE id_grupo IN ('.$id_groups.')' ); if ($agents === false) { @@ -14089,7 +14863,6 @@ function api_set_update_event_filter($id_event_filter, $thrash1, $other, $thrash break; case 20: - print_r('adadadasds'); $values['user_comment'] = $other['data'][20]; break; } @@ -14478,7 +15251,7 @@ function api_get_group_id_by_name($thrash1, $thrash2, $other, $thrash3) $sql = sprintf( 'SELECT id_grupo - FROM tgrupo WHERE nombre = "'.$other['data'].'"' + FROM tgrupo WHERE nombre = "'.$other['data'].'"' ); $group_id = db_get_all_rows_sql($sql); @@ -14504,7 +15277,7 @@ function api_get_timezone($thrash1, $thrash2, $other, $thrash3) $sql = sprintf( 'SELECT value - FROM tconfig WHERE token = "timezone"' + FROM tconfig WHERE token = "timezone"' ); $timezone = db_get_all_rows_sql($sql); @@ -14530,7 +15303,7 @@ function api_get_language($thrash1, $thrash2, $other, $thrash3) $sql = sprintf( 'SELECT value - FROM tconfig WHERE token = "language"' + FROM tconfig WHERE token = "language"' ); $language = db_get_all_rows_sql($sql); @@ -14556,7 +15329,7 @@ function api_get_session_timeout($thrash1, $thrash2, $other, $thrash3) $sql = sprintf( 'SELECT value - FROM tconfig WHERE token = "session_timeout"' + FROM tconfig WHERE token = "session_timeout"' ); $language = db_get_all_rows_sql($sql); diff --git a/pandora_console/include/functions_config.php b/pandora_console/include/functions_config.php index f59061a03c..6563a6def2 100644 --- a/pandora_console/include/functions_config.php +++ b/pandora_console/include/functions_config.php @@ -325,6 +325,34 @@ function config_update_config() if (!config_update_value('unique_ip', get_parameter('unique_ip'))) { $error_update[] = __('unique_ip'); } + + if (!config_update_value('email_smtpServer', get_parameter('email_smtpServer'))) { + $error_update[] = __('Server SMTP'); + } + + if (!config_update_value('email_from_dir', get_parameter('email_from_dir'))) { + $error_update[] = __('From dir'); + } + + if (!config_update_value('email_from_name', get_parameter('email_from_name'))) { + $error_update[] = __('From name'); + } + + if (!config_update_value('email_smtpPort', (int) get_parameter('email_smtpPort'))) { + $error_update[] = __('Port SMTP'); + } + + if (!config_update_value('email_encryption', get_parameter('email_encryption'))) { + $error_update[] = __('Encryption'); + } + + if (!config_update_value('email_username', get_parameter('email_username'))) { + $error_update[] = __('Email user'); + } + + if (!config_update_value('email_password', get_parameter('email_password'))) { + $error_update[] = __('Email password'); + } break; case 'enterprise': @@ -419,34 +447,6 @@ function config_update_config() if (!config_update_value('inventory_changes_blacklist', implode(',', $inventory_changes_blacklist))) { $error_update[] = __('Inventory changes blacklist'); } - - if (!config_update_value('email_from_dir', get_parameter('email_from_dir'))) { - $error_update[] = __('From dir'); - } - - if (!config_update_value('email_from_name', get_parameter('email_from_name'))) { - $error_update[] = __('From name'); - } - - if (!config_update_value('email_smtpServer', get_parameter('email_smtpServer'))) { - $error_update[] = __('Server SMTP'); - } - - if (!config_update_value('email_smtpPort', (int) get_parameter('email_smtpPort'))) { - $error_update[] = __('Port SMTP'); - } - - if (!config_update_value('email_encryption', get_parameter('email_encryption'))) { - $error_update[] = __('Encryption'); - } - - if (!config_update_value('email_username', get_parameter('email_username'))) { - $error_update[] = __('Email user'); - } - - if (!config_update_value('email_password', get_parameter('email_password'))) { - $error_update[] = __('Email password'); - } } break; @@ -1434,6 +1434,92 @@ function config_update_config() } break; + case 'integria': + if (!config_update_value('integria_enabled', (int) get_parameter('integria_enabled', 0))) { + $error_update[] = __('Enable Integria IMS'); + } + + if (!config_update_value('integria_user', (string) get_parameter('integria_user', $config['integria_user']))) { + $error_update[] = __('Integria user'); + } + + if (!config_update_value('integria_pass', io_input_password((string) get_parameter('integria_pass', $config['integria_pass'])))) { + $error_update[] = __('Integria password'); + } + + if (!config_update_value('integria_hostname', (string) get_parameter('integria_hostname', $config['integria_hostname']))) { + $error_update[] = __('integria API hostname'); + } + + if (!config_update_value('integria_api_pass', io_input_password((string) get_parameter('integria_api_pass', $config['integria_api_pass'])))) { + $error_update[] = __('Integria API password'); + } + + if (!config_update_value('integria_req_timeout', (int) get_parameter('integria_req_timeout', $config['integria_req_timeout']))) { + $error_update[] = __('Integria request timeout'); + } + + if (!config_update_value('default_group', (int) get_parameter('default_group', $config['default_group']))) { + $error_update[] = __('Integria default group'); + } + + if (!config_update_value('cr_default_group', (int) get_parameter('cr_default_group', $config['cr_default_group']))) { + $error_update[] = __('Integria custom response default group'); + } + + if (!config_update_value('default_criticity', (int) get_parameter('default_criticity', $config['default_criticity']))) { + $error_update[] = __('Integria default priority'); + } + + if (!config_update_value('cr_default_criticity', (int) get_parameter('cr_default_criticity', $config['cr_default_criticity']))) { + $error_update[] = __('Integria custom response default priority'); + } + + if (!config_update_value('default_creator', (string) get_parameter('default_creator', $config['default_creator']))) { + $error_update[] = __('Integria default creator'); + } + + if (!config_update_value('default_owner', (string) get_parameter('default_owner', $config['default_owner']))) { + $error_update[] = __('Integria default owner'); + } + + if (!config_update_value('cr_default_owner', (string) get_parameter('cr_default_owner', $config['cr_default_owner']))) { + $error_update[] = __('Integria custom response default owner'); + } + + if (!config_update_value('incident_type', (int) get_parameter('incident_type', $config['incident_type']))) { + $error_update[] = __('Integria default ticket type'); + } + + if (!config_update_value('cr_incident_type', (int) get_parameter('cr_incident_type', $config['cr_incident_type']))) { + $error_update[] = __('Integria custom response default ticket type'); + } + + if (!config_update_value('incident_status', (int) get_parameter('incident_status', $config['incident_status']))) { + $error_update[] = __('Integria default ticket status'); + } + + if (!config_update_value('cr_incident_status', (int) get_parameter('cr_incident_status', $config['cr_incident_status']))) { + $error_update[] = __('Integria custom response default ticket status'); + } + + if (!config_update_value('incident_title', (string) get_parameter('incident_title', $config['incident_title']))) { + $error_update[] = __('Integria default ticket title'); + } + + if (!config_update_value('cr_incident_title', (string) get_parameter('cr_incident_title', $config['cr_incident_title']))) { + $error_update[] = __('Integria custom response default ticket title'); + } + + if (!config_update_value('incident_content', (string) get_parameter('incident_content', $config['incident_content']))) { + $error_update[] = __('Integria default ticket content'); + } + + if (!config_update_value('cr_incident_content', (string) get_parameter('cr_incident_content', $config['cr_incident_content']))) { + $error_update[] = __('Integria custom response default ticket content'); + } + break; + default: // Ignore. break; @@ -1500,7 +1586,7 @@ function config_process_config() if (!isset($config['remote_config'])) { if ($is_windows) { - $default = 'C:\\PandoraFMS\\Pandora_Server\\data_in'; + $default = 'C:\PandoraFMS\Pandora_Server\data_in'; } else { $default = '/var/spool/pandora/data_in'; } @@ -1510,7 +1596,7 @@ function config_process_config() if (!isset($config['phantomjs_bin'])) { if ($is_windows) { - $default = 'C:\\PandoraFMS\\phantomjs'; + $default = 'C:\PandoraFMS\Pandora_Server\bin'; } else { $default = '/usr/bin'; } @@ -1760,7 +1846,13 @@ function config_process_config() } if (!isset($config['auditdir'])) { - config_update_value('auditdir', '/var/www/html/pandora_console'); + $auditdir = '/var/www/html/pandora_console'; + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + // Windows. + $auditdir = $config['homedir']; + } + + config_update_value('auditdir', $auditdir); } if (!isset($config['elasticsearch_ip'])) { @@ -1794,6 +1886,7 @@ function config_process_config() /* * Parse the ACL IP list for access API */ + $temp_list_ACL_IPs_for_API = []; if (isset($config['list_ACL_IPs_for_API'])) { if (!empty($config['list_ACL_IPs_for_API'])) { @@ -1804,13 +1897,16 @@ function config_process_config() $config['list_ACL_IPs_for_API'] = $temp_list_ACL_IPs_for_API; $keysConfig = array_keys($config); - // This is not set here. The first time, when no - // setup is done, update_manager extension manage it - // the first time make a conenction and disable itself - // Not Managed here ! - // if (!isset ($config["autoupdate"])) { - // config_update_value ('autoupdate', true);. - // } + /* + * This is not set here. The first time, when no + * setup is done, update_manager extension manage it + * the first time make a conenction and disable itself + * Not Managed here ! + * if (!isset ($config["autoupdate"])) { + * config_update_value ('autoupdate', true);. + * } + */ + include_once $config['homedir'].'/include/auth/mysql.php'; include_once $config['homedir'].'/include/functions_io.php'; @@ -1819,10 +1915,16 @@ function config_process_config() // user, and should be in pandora root. By default, Pandora adds // /attachment to this, so by default is the pandora console home // dir. + $attachment_store_path = $config['homedir'].'/attachment'; + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + // Windows. + $attachment_store_path = $config['homedir'].'\attachment'; + } + if (!isset($config['attachment_store'])) { config_update_value( 'attachment_store', - io_safe_input($config['homedir']).'/attachment' + $attachment_store_path ); } else { // Fixed when the user moves the pandora console to another dir @@ -1830,16 +1932,23 @@ function config_process_config() if (!is_dir($config['attachment_store'])) { config_update_value( 'attachment_store', - $config['homedir'].'/attachment' + $attachment_store_path ); } } if (!isset($config['fontpath'])) { - $home = str_replace('\\', '/', $config['homedir']); + if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { + // Windows. + $fontpath = $config['homedir'].'\include\fonts\smallfont.ttf'; + } else { + $home = str_replace('\\', '/', $config['homedir']); + $fontpath = $home.'/include/fonts/smallfont.ttf'; + } + config_update_value( 'fontpath', - $home.'/include/fonts/smallfont.ttf' + $fontpath ); } @@ -2077,7 +2186,7 @@ function config_process_config() if (!isset($config['netflow_path'])) { if ($is_windows) { - $default = 'C:\\PandoraFMS\\Pandora_Server\\data_in\\netflow'; + $default = 'C:\PandoraFMS\Pandora_Server\data_in\netflow'; } else { $default = '/var/spool/pandora/data_in/netflow'; } @@ -2639,6 +2748,10 @@ function config_process_config() config_update_value('zoom_graph', 1); } + if (!isset($config['percentil'])) { + config_update_value('percentil', 95); + } + if (!isset($config['render_proc_ok'])) { config_update_value('render_proc_ok', __('Ok')); } @@ -2820,6 +2933,19 @@ function config_process_config() } } + // Integria. + if (!isset($config['integria_enabled'])) { + config_update_value('integria_enabled', 0); + } + + if (!isset($config['integria_req_timeout'])) { + config_update_value('integria_req_timeout', 5); + } + + if (!isset($config['integria_hostname'])) { + config_update_value('integria_hostname', ''); + } + // Finally, check if any value was overwritten in a form. config_update_config(); } diff --git a/pandora_console/include/functions_credential_store.php b/pandora_console/include/functions_credential_store.php index 1b64bba116..033743130a 100644 --- a/pandora_console/include/functions_credential_store.php +++ b/pandora_console/include/functions_credential_store.php @@ -24,422 +24,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * ============================================================================ + * + * Moved to CredentialStore.class.php */ -// Begin. - - -/** - * Returns an array with all the credentials matching filter and ACL. - * - * @param array $fields Fields array or 'count' keyword to retrieve count. - * @param array $filter Filters to be applied. - * @param integer $offset Offset (pagination). - * @param integer $limit Limit (pagination). - * @param string $order Sort order. - * @param string $sort_field Sort field. - * - * @return array With all results or false if error. - * @throws Exception On error. - */ -function credentials_get_all( - $fields, - array $filter, - $offset=null, - $limit=null, - $order=null, - $sort_field=null -) { - $sql_filters = []; - $order_by = ''; - $pagination = ''; - - global $config; - - if (!is_array($filter)) { - error_log('[credential_get_all] Filter must be an array.'); - throw new Exception('[credential_get_all] Filter must be an array.'); - } - - $count = false; - if (!is_array($fields) && $fields == 'count') { - $fields = ['cs.*']; - $count = true; - } else if (!is_array($fields)) { - error_log('[credential_get_all] Fields must be an array or "count".'); - throw new Exception('[credential_get_all] Fields must be an array or "count".'); - } - - if (isset($filter['product']) && !empty($filter['product'])) { - $sql_filters[] = sprintf(' AND cs.product = "%s"', $filter['product']); - } - - if (isset($filter['free_search']) && !empty($filter['free_search'])) { - $sql_filters[] = vsprintf( - ' AND (lower(cs.username) like lower("%%%s%%") - OR cs.identifier like "%%%s%%" - OR lower(cs.product) like lower("%%%s%%"))', - array_fill(0, 3, $filter['free_search']) - ); - } - - if (isset($filter['filter_id_group']) && $filter['filter_id_group'] > 0) { - $propagate = db_get_value( - 'propagate', - 'tgrupo', - 'id_grupo', - $filter['filter_id_group'] - ); - - if (!$propagate) { - $sql_filters[] = sprintf( - ' AND cs.id_group = %d ', - $filter['filter_id_group'] - ); - } else { - $groups = [ $filter['filter_id_group'] ]; - $childrens = groups_get_childrens($id_group, null, true); - if (!empty($childrens)) { - foreach ($childrens as $child) { - $groups[] = (int) $child['id_grupo']; - } - } - - $filter['filter_id_group'] = $groups; - $sql_filters[] = sprintf( - ' AND cs.id_group IN (%s) ', - join(',', $filter['filter_id_group']) - ); - } - } - - if (isset($filter['group_list']) && is_array($filter['group_list'])) { - $sql_filters[] = sprintf( - ' AND cs.id_group IN (%s) ', - join(',', $filter['group_list']) - ); - } - - if (isset($order)) { - $dir = 'asc'; - if ($order == 'desc') { - $dir = 'desc'; - }; - - if (in_array( - $sort_field, - [ - 'group', - 'identifier', - 'product', - 'username', - 'options', - ] - ) - ) { - $order_by = sprintf( - 'ORDER BY `%s` %s', - $sort_field, - $dir - ); - } - } - - if (isset($limit) && $limit > 0 - && isset($offset) && $offset >= 0 - ) { - $pagination = sprintf( - ' LIMIT %d OFFSET %d ', - $limit, - $offset - ); - } - - $sql = sprintf( - 'SELECT %s - FROM tcredential_store cs - LEFT JOIN tgrupo tg - ON tg.id_grupo = cs.id_group - WHERE 1=1 - %s - %s - %s', - join(',', $fields), - join(' ', $sql_filters), - $order_by, - $pagination - ); - - if ($count) { - $sql = sprintf('SELECT count(*) as n FROM ( %s ) tt', $sql); - - return db_get_value_sql($sql); - } - - return db_get_all_rows_sql($sql); -} - - -/** - * Retrieves target key from keystore or false in case of error. - * - * @param string $identifier Key identifier. - * - * @return array Key or false if error. - */ -function get_key($identifier) -{ - return db_get_row_filter( - 'tcredential_store', - [ 'identifier' => $identifier ] - ); -} - - -/** - * Minor function to dump json message as ajax response. - * - * @param string $type Type: result || error. - * @param string $msg Message. - * @param boolean $delete Deletion messages. - * - * @return void - */ -function ajax_msg($type, $msg, $delete=false) -{ - $msg_err = 'Failed while saving: %s'; - $msg_ok = 'Successfully saved into keystore '; - - if ($delete) { - $msg_err = 'Failed while removing: %s'; - $msg_ok = 'Successfully deleted '; - } - - if ($type == 'error') { - echo json_encode( - [ - $type => ui_print_error_message( - __( - $msg_err, - $msg - ), - '', - true - ), - ] - ); - } else { - echo json_encode( - [ - $type => ui_print_success_message( - __( - $msg_ok, - $msg - ), - '', - true - ), - ] - ); - } - - exit; -} - - -/** - * Generates inputs for new/update forms. - * - * @param array $values Values or null. - * - * @return string Inputs. - */ -function print_inputs($values=null) -{ - if (!is_array($values)) { - $values = []; - } - - $return = ''; - $return .= html_print_input( - [ - 'label' => __('Identifier'), - 'name' => 'identifier', - 'input_class' => 'flex-row', - 'type' => 'text', - 'value' => $values['identifier'], - 'disabled' => (bool) $values['identifier'], - 'return' => true, - 'script' => 'alert(\'puta\')', - ] - ); - $return .= html_print_input( - [ - 'label' => __('Group'), - 'name' => 'id_group', - 'id' => 'id_group', - 'input_class' => 'flex-row', - 'type' => 'select_groups', - 'selected' => $values['id_group'], - 'return' => true, - 'class' => 'w50p', - ] - ); - $return .= html_print_input( - [ - 'label' => __('Product'), - 'name' => 'product', - 'input_class' => 'flex-row', - 'type' => 'select', - 'script' => 'calculate_inputs()', - 'fields' => [ - 'CUSTOM' => __('Custom'), - 'AWS' => __('Aws'), - 'AZURE' => __('Azure'), - // 'GOOGLE' => __('Google'), - ], - 'selected' => $values['product'], - 'disabled' => (bool) $values['product'], - 'return' => true, - ] - ); - $user_label = __('Username'); - $pass_label = __('Password'); - $extra_1_label = __('Extra'); - $extra_2_label = __('Extra (2)'); - $extra1 = true; - $extra2 = true; - - // Remember to update credential_store.php also. - switch ($values['product']) { - case 'AWS': - $user_label = __('Access key ID'); - $pass_label = __('Secret access key'); - $extra1 = false; - $extra2 = false; - break; - - case 'AZURE': - $user_label = __('Account ID'); - $pass_label = __('Application secret'); - $extra_1_label = __('Tenant or domain name'); - $extra_2_label = __('Subscription id'); - break; - - case 'GOOGLE': - // Need further investigation. - case 'CUSTOM': - $user_label = __('Account ID'); - $pass_label = __('Password'); - $extra1 = false; - $extra2 = false; - default: - // Use defaults. - break; - } - - $return .= html_print_input( - [ - 'label' => $user_label, - 'name' => 'username', - 'input_class' => 'flex-row', - 'type' => 'text', - 'value' => $values['username'], - 'return' => true, - ] - ); - $return .= html_print_input( - [ - 'label' => $pass_label, - 'name' => 'password', - 'input_class' => 'flex-row', - 'type' => 'password', - 'value' => $values['password'], - 'return' => true, - ] - ); - if ($extra1) { - $return .= html_print_input( - [ - 'label' => $extra_1_label, - 'name' => 'extra_1', - 'input_class' => 'flex-row', - 'type' => 'text', - 'value' => $values['extra_1'], - 'return' => true, - ] - ); - } - - if ($extra2) { - $return .= html_print_input( - [ - 'label' => $extra_2_label, - 'name' => 'extra_2', - 'input_class' => 'flex-row', - 'type' => 'text', - 'value' => $values['extra_2'], - 'return' => true, - 'display' => $extra2, - ] - ); - } - - return $return; -} - - -/** - * Retrieve all identifiers available for current user. - * - * @param string $product Target product. - * - * @return array Of account identifiers. - */ -function credentials_list_accounts($product) -{ - global $config; - - check_login(); - - include_once $config['homedir'].'/include/functions_users.php'; - - static $user_groups; - - if (!isset($user_groups)) { - $user_groups = users_get_groups( - $config['id_user'], - 'AR' - ); - - // Always add group 'ALL' because 'ALL' group credentials - // must be available for all users. - if (is_array($user_groups)) { - $user_groups = ([0] + array_keys($user_groups)); - } else { - $user_groups = [0]; - } - } - - $creds = credentials_get_all( - ['identifier'], - [ - 'product' => $product, - 'group_list' => $user_groups, - ] - ); - - if ($creds === false) { - return []; - } - - $ret = array_reduce( - $creds, - function ($carry, $item) { - $carry[$item['identifier']] = $item['identifier']; - return $carry; - } - ); - - return $ret; -} +// Deprecated. diff --git a/pandora_console/include/functions_custom_graphs.php b/pandora_console/include/functions_custom_graphs.php index 4a1c5df11c..45341efbb3 100644 --- a/pandora_console/include/functions_custom_graphs.php +++ b/pandora_console/include/functions_custom_graphs.php @@ -124,8 +124,26 @@ function custom_graphs_get_user($id_user=0, $only_names=false, $returnAllGroup=t } $groups = users_get_groups($id_user, $privileges, $returnAllGroup); + $all_graphs = []; + if (is_metaconsole()) { + $servers = metaconsole_get_connection_names(); + foreach ($servers as $key => $server) { + $connection = metaconsole_get_connection($server); + if (metaconsole_connect($connection) != NOERR) { + continue; + } + + $all_graph = db_get_all_rows_in_table('tgraph', 'name'); + if ($all_graph !== false) { + $all_graphs = array_merge($all_graphs, $all_graph); + } + + metaconsole_restore_db(); + } + } else { + $all_graphs = db_get_all_rows_in_table('tgraph', 'name'); + } - $all_graphs = db_get_all_rows_in_table('tgraph', 'name'); if ($all_graphs === false) { return []; } diff --git a/pandora_console/include/functions_db.php b/pandora_console/include/functions_db.php index 3efbf59628..a99ab2e41e 100644 --- a/pandora_console/include/functions_db.php +++ b/pandora_console/include/functions_db.php @@ -46,6 +46,25 @@ function db_select_engine() } +/** + * Connects to target DB. + * + * @param array $setup Database definition. + * + * @return mixed Dbconnection or null. + */ +function get_dbconnection(array $setup) +{ + return mysqli_connect( + $setup['dbhost'], + $setup['dbuser'], + $setup['dbpass'], + $setup['dbname'], + $setup['dbport'] + ); +} + + function db_connect($host=null, $db=null, $user=null, $pass=null, $port=null, $critical=true, $charset=null) { global $config; diff --git a/pandora_console/include/functions_events.php b/pandora_console/include/functions_events.php index ffb36aa3ae..9563732c68 100644 --- a/pandora_console/include/functions_events.php +++ b/pandora_console/include/functions_events.php @@ -2739,6 +2739,10 @@ function events_get_agent( $date = time_w_fixed_tz($date); } + if (is_metaconsole() && $events_group === false) { + $id_server = true; + } + if (empty($date)) { $date = get_system_time(); } @@ -4378,7 +4382,7 @@ function events_page_general($event) $data = []; $data[0] = __('Event name'); - $data[1] = events_display_name($event['evento']); + $data[1] = ''.events_display_name($event['evento']).''; $table_general->data[] = $data; $data = []; @@ -4611,7 +4615,7 @@ function events_page_comments($event, $ajax=false) foreach ($comm as $c) { $data[0] = ''.$c['action'].' by '.$c['id_user'].''; $data[0] .= '

'.date($config['date_format'], $c['utimestamp']).''; - $data[1] = $c['comment']; + $data[1] = '

'.$c['comment'].'

'; $table_comments->data[] = $data; } } @@ -6634,3 +6638,297 @@ function events_get_secondary_groups_left_join($table) return 'LEFT JOIN tmetaconsole_agent_secondary_group tasg ON te.id_agente = tasg.id_tagente AND te.server_id = tasg.id_tmetaconsole_setup'; } + + +/** + * Replace macros in any string given an event id. + * If server_id > 0, it's a metaconsole query. + * + * @param integer $event_id Event identifier. + * @param integer $value String value in which we want to apply macros. + * + * @return string The response text with the macros applied. + */ +function events_get_field_value_by_event_id( + int $event_id, + $value +) { + global $config; + + $meta = false; + $event = db_get_row('tevento', 'id_evento', $event_id); + + // Replace each macro. + if (strpos($value, '_agent_address_') !== false) { + if ($meta) { + $agente_table_name = 'tmetaconsole_agent'; + $filter = [ + 'id_tagente' => $event['id_agente'], + 'id_tmetaconsole_setup' => $server_id, + ]; + } else { + $agente_table_name = 'tagente'; + $filter = ['id_agente' => $event['id_agente']]; + } + + $ip = db_get_value_filter('direccion', $agente_table_name, $filter); + // If agent does not have an IP, display N/A. + if ($ip === false) { + $ip = __('N/A'); + } + + $value = str_replace('_agent_address_', $ip, $value); + } + + if (strpos($value, '_agent_id_') !== false) { + $value = str_replace('_agent_id_', $event['id_agente'], $value); + } + + if (strpos($value, '_module_address_') !== false) { + if ($event['id_agentmodule'] != 0) { + if ($meta) { + $server = metaconsole_get_connection_by_id($server_id); + metaconsole_connect($server); + } + + $module = db_get_row('tagente_modulo', 'id_agente_modulo', $event['id_agentmodule']); + if (empty($module['ip_target'])) { + $module['ip_target'] = __('N/A'); + } + + $value = str_replace('_module_address_', $module['ip_target'], $value); + if (empty($module['nombre'])) { + $module['nombre'] = __('N/A'); + } + + if ($meta) { + metaconsole_restore_db(); + } + } else { + $value = str_replace('_module_address_', __('N/A'), $value); + } + } + + if (strpos($value, '_module_name_') !== false) { + if ($event['id_agentmodule'] != 0) { + if ($meta) { + $server = metaconsole_get_connection_by_id($server_id); + metaconsole_connect($server); + } + + $module = db_get_row('tagente_modulo', 'id_agente_modulo', $event['id_agentmodule']); + if (empty($module['ip_target'])) { + $module['ip_target'] = __('N/A'); + } + + $value = str_replace( + '_module_name_', + io_safe_output($module['nombre']), + $value + ); + + if ($meta) { + metaconsole_restore_db(); + } + } else { + $value = str_replace('_module_name_', __('N/A'), $value); + } + } + + if (strpos($value, '_event_id_') !== false) { + $value = str_replace('_event_id_', $event['id_evento'], $value); + } + + if (strpos($value, '_user_id_') !== false) { + if (!empty($event['id_usuario'])) { + $value = str_replace('_user_id_', $event['id_usuario'], $value); + } else { + $value = str_replace('_user_id_', __('N/A'), $value); + } + } + + if (strpos($value, '_group_id_') !== false) { + $value = str_replace('_group_id_', $event['id_grupo'], $value); + } + + if (strpos($value, '_group_name_') !== false) { + $value = str_replace( + '_group_name_', + groups_get_name($event['id_grupo'], true), + $value + ); + } + + if (strpos($value, '_event_utimestamp_') !== false) { + $value = str_replace( + '_event_utimestamp_', + $event['utimestamp'], + $value + ); + } + + if (strpos($value, '_event_date_') !== false) { + $value = str_replace( + '_event_date_', + date($config['date_format'], $event['utimestamp']), + $value + ); + } + + if (strpos($value, '_event_text_') !== false) { + $value = str_replace( + '_event_text_', + events_display_name($event['evento']), + $value + ); + } + + if (strpos($value, '_event_type_') !== false) { + $value = str_replace( + '_event_type_', + events_print_type_description($event['event_type'], true), + $value + ); + } + + if (strpos($value, '_alert_id_') !== false) { + $value = str_replace( + '_alert_id_', + empty($event['is_alert_am']) ? __('N/A') : $event['is_alert_am'], + $value + ); + } + + if (strpos($value, '_event_severity_id_') !== false) { + $value = str_replace('_event_severity_id_', $event['criticity'], $value); + } + + if (strpos($value, '_event_severity_text_') !== false) { + $value = str_replace( + '_event_severity_text_', + get_priority_name($event['criticity']), + $value + ); + } + + if (strpos($value, '_module_id_') !== false) { + $value = str_replace('_module_id_', $event['id_agentmodule'], $value); + } + + if (strpos($value, '_event_tags_') !== false) { + $value = str_replace('_event_tags_', $event['tags'], $value); + } + + if (strpos($value, '_event_extra_id_') !== false) { + if (empty($event['id_extra'])) { + $value = str_replace('_event_extra_id_', __('N/A'), $value); + } else { + $value = str_replace('_event_extra_id_', $event['id_extra'], $value); + } + } + + if (strpos($value, '_event_source_') !== false) { + $value = str_replace('_event_source_', $event['source'], $value); + } + + if (strpos($value, '_event_instruction_') !== false) { + $value = str_replace( + '_event_instruction_', + events_display_instructions($event['event_type'], $event, false), + $value + ); + } + + if (strpos($value, '_owner_user_') !== false) { + if (empty($event['owner_user'])) { + $value = str_replace('_owner_user_', __('N/A'), $value); + } else { + $value = str_replace('_owner_user_', $event['owner_user'], $value); + } + } + + if (strpos($value, '_event_status_') !== false) { + $event_st = events_display_status($event['estado']); + $value = str_replace('_event_status_', $event_st['title'], $value); + } + + if (strpos($value, '_group_custom_id_') !== false) { + $group_custom_id = db_get_value_sql( + sprintf( + 'SELECT custom_id FROM tgrupo WHERE id_grupo=%s', + $event['id_grupo'] + ) + ); + $event_st = events_display_status($event['estado']); + $value = str_replace('_group_custom_id_', $group_custom_id, $value); + } + + // Parse the event custom data. + if (!empty($event['custom_data'])) { + $custom_data = json_decode(base64_decode($event['custom_data'])); + foreach ($custom_data as $key => $val) { + $value = str_replace('_customdata_'.$key.'_', $val, $value); + } + } + + // This will replace the macro with the current logged user. + if (strpos($value, '_current_user_') !== false) { + $value = str_replace('_current_user_', $config['id_user'], $value); + } + + return $value; + +} + + +function events_get_instructions($event) +{ + if (!is_array($event)) { + return ''; + } + + switch ($event['event_type']) { + case 'going_unknown': + if ($event['unknown_instructions'] != '') { + $value = str_replace("\n", '
', io_safe_output($event['unknown_instructions'])); + } + break; + + case 'going_up_warning': + case 'going_down_warning': + if ($event['warning_instructions'] != '') { + $value = str_replace("\n", '
', io_safe_output($event['warning_instructions'])); + } + break; + + case 'going_up_critical': + case 'going_down_critical': + if ($event['critical_instructions'] != '') { + $value = str_replace("\n", '
', io_safe_output($event['critical_instructions'])); + } + break; + } + + if (!isset($value)) { + return ''; + } + + $max_text_length = 300; + $over_text = io_safe_output($value); + if (strlen($over_text) > ($max_text_length + 3)) { + $over_text = substr($over_text, 0, $max_text_length).'...'; + } + + $output = '
'; + $output .= ''; + $output .= ''; + $output .= html_print_image('images/default_list.png', true, ['title' => $over_text]).''; + $output .= ''; + + return $output; +} diff --git a/pandora_console/include/functions_events.php.orig b/pandora_console/include/functions_events.php.orig new file mode 100644 index 0000000000..6ec9d42dfe --- /dev/null +++ b/pandora_console/include/functions_events.php.orig @@ -0,0 +1,6934 @@ + 0]; + } + + $table = events_get_events_table(is_metaconsole(), $history); + + switch ($filter['group_rep']) { + case '0': + case '2': + default: + // No groups option direct update. + $delete_sql = sprintf( + 'DELETE FROM %s + WHERE id_evento = %d', + $table, + $id_evento + ); + break; + + case '1': + // Group by events. + $sql = events_get_all( + ['te.*'], + $filter, + // Offset. + null, + // Limit. + null, + // Order. + null, + // Sort_field. + null, + // Historical table. + $history, + // Return_sql. + true + ); + + $target_ids = db_get_all_rows_sql( + sprintf( + 'SELECT tu.id_evento FROM %s tu INNER JOIN ( %s ) tf + ON tu.estado = tf.estado + AND tu.evento = tf.evento + AND tu.id_agente = tf.id_agente + AND tu.id_agentmodule = tf.id_agentmodule + AND tf.max_id_evento = %d', + $table, + $sql, + $id_evento + ) + ); + + // Try to avoid deadlock while updating full set. + if ($target_ids !== false && count($target_ids) > 0) { + $target_ids = array_reduce( + $target_ids, + function ($carry, $item) { + $carry[] = $item['id_evento']; + return $carry; + } + ); + + $delete_sql = sprintf( + 'DELETE FROM %s WHERE id_evento IN (%s)', + $table, + join(', ', $target_ids) + ); + } + break; + } + + return db_process_sql($delete_sql); +} + + +/** + * Retrieves all events related to matching one. + * + * @param integer $id_evento Master event (max_id_evento). + * @param array $filter Filters. + * @param boolean $count Count results or get results. + * @param boolean $history Apply on historical table. + * + * @return array Events or false in case of error. + */ +function events_get_related_events( + $id_evento, + $filter=null, + $count=false, + $history=false +) { + global $config; + + if (!isset($id_evento) || $id_evento <= 0) { + return false; + } + + if (!isset($filter) || !is_array($filter)) { + $filter = ['group_rep' => 0]; + } + + $table = events_get_events_table(is_metaconsole(), $history); + $select = '*'; + if ($count === true) { + $select = 'count(*) as n'; + }; + + switch ($filter['group_rep']) { + case '0': + case '2': + default: + // No groups option direct update. + $related_sql = sprintf( + 'SELECT %s FROM %s + WHERE id_evento = %d', + $select, + $table, + $id_evento + ); + break; + + case '1': + // Group by events. + $sql = events_get_all( + ['te.*'], + $filter, + // Offset. + null, + // Limit. + null, + // Order. + null, + // Sort_field. + null, + // Historical table. + $history, + // Return_sql. + true + ); + $related_sql = sprintf( + 'SELECT %s FROM %s tu INNER JOIN ( %s ) tf + WHERE tu.estado = tf.estado + AND tu.evento = tf.evento + AND tu.id_agente = tf.id_agente + AND tu.id_agentmodule = tf.id_agentmodule + AND tf.max_id_evento = %d', + $select, + $table, + $sql, + $id_evento + ); + break; + } + + if ($count === true) { + $r = db_get_all_rows_sql($related_sql); + + return $r[0]['n']; + } + + return db_get_all_rows_sql($related_sql); + +} + + +/** + * Validates all events matching target filter. + * + * @param integer $id_evento Master event. + * @param integer $status Target status. + * @param array $filter Optional. Filter options. + * @param boolean $history Apply on historical table. + * + * @return integer Events validated or false if error. + */ +function events_update_status($id_evento, $status, $filter=null, $history=false) +{ + global $config; + + if (!$status) { + error_log('No hay estado'); + return false; + } + + if (!isset($id_evento) || $id_evento <= 0) { + error_log('No hay id_evento'); + return false; + } + + if (!isset($filter) || !is_array($filter)) { + $filter = ['group_rep' => 0]; + } + + $table = events_get_events_table(is_metaconsole(), $history); + + switch ($filter['group_rep']) { + case '0': + case '2': + default: + // No groups option direct update. + $update_sql = sprintf( + 'UPDATE %s + SET estado = %d + WHERE id_evento = %d', + $table, + $status, + $id_evento + ); + break; + + case '1': + // Group by events. + $sql = events_get_all( + ['te.*'], + $filter, + // Offset. + null, + // Limit. + null, + // Order. + null, + // Sort_field. + null, + // Historical table. + $history, + // Return_sql. + true + ); + + $target_ids = db_get_all_rows_sql( + sprintf( + 'SELECT tu.id_evento FROM %s tu INNER JOIN ( %s ) tf + ON tu.estado = tf.estado + AND tu.evento = tf.evento + AND tu.id_agente = tf.id_agente + AND tu.id_agentmodule = tf.id_agentmodule + AND tf.max_id_evento = %d', + $table, + $sql, + $id_evento + ) + ); + + // Try to avoid deadlock while updating full set. + if ($target_ids !== false && count($target_ids) > 0) { + $target_ids = array_reduce( + $target_ids, + function ($carry, $item) { + $carry[] = $item['id_evento']; + return $carry; + } + ); + + $update_sql = sprintf( + 'UPDATE %s + SET estado = %d, + ack_utimestamp = %d, + id_usuario = "%s" + WHERE id_evento IN (%s)', + $table, + $status, + time(), + $config['id_user'], + join(',', $target_ids) + ); + } + break; + } + + return db_process_sql($update_sql); +} + + +/** + * Retrieve all events filtered. + * + * @param array $fields Fields to retrieve. + * @param array $filter Filters to be applied. + * @param integer $offset Offset (pagination). + * @param integer $limit Limit (pagination). + * @param string $order Sort order. + * @param string $sort_field Sort field. + * @param boolean $history Apply on historical table. + * @param boolean $return_sql Return SQL (true) or execute it (false). + * @param string $having Having filter. + * + * @return array Events. + * @throws Exception On error. + */ +function events_get_all( + $fields, + array $filter, + $offset=null, + $limit=null, + $order=null, + $sort_field=null, + $history=false, + $return_sql=false, + $having='' +) { + global $config; + + $user_is_admin = users_is_admin(); + + if (!is_array($filter)) { + error_log('[events_get_all] Filter must be an array.'); + throw new Exception('[events_get_all] Filter must be an array.'); + } + + $count = false; + if (!is_array($fields) && $fields == 'count') { + $fields = ['te.*']; + $count = true; + } else if (!is_array($fields)) { + error_log('[events_get_all] Fields must be an array or "count".'); + throw new Exception('[events_get_all] Fields must be an array or "count".'); + } + + if (isset($filter['date_from']) + && !empty($filter['date_from']) + && $filter['date_from'] != '0000-00-00' + ) { + $date_from = $filter['date_from']; + } + + if (isset($filter['time_from'])) { + $time_from = $filter['time_from']; + } + + if (isset($date_from)) { + if (!isset($time_from)) { + $time_from = '00:00:00'; + } + + $from = $date_from.' '.$time_from; + $sql_filters[] = sprintf( + ' AND te.utimestamp >= %d', + strtotime($from) + ); + } + + if (isset($filter['date_to']) + && !empty($filter['date_to']) + && $filter['date_to'] != '0000-00-00' + ) { + $date_to = $filter['date_to']; + } + + if (isset($filter['time_to'])) { + $time_to = $filter['time_to']; + } + + if (isset($date_to)) { + if (!isset($time_to)) { + $time_to = '23:59:59'; + } + + $to = $date_to.' '.$time_to; + $sql_filters[] = sprintf( + ' AND te.utimestamp <= %d', + strtotime($to) + ); + } + + if (!isset($from)) { + if (isset($filter['event_view_hr']) && ($filter['event_view_hr'] > 0)) { + $sql_filters[] = sprintf( + ' AND utimestamp > UNIX_TIMESTAMP(now() - INTERVAL %d HOUR) ', + $filter['event_view_hr'] + ); + } + } + + if (isset($filter['id_agent']) && $filter['id_agent'] > 0) { + $sql_filters[] = sprintf( + ' AND te.id_agente = %d ', + $filter['id_agent'] + ); + } + + if (!empty($filter['event_type']) && $filter['event_type'] != 'all') { + if ($filter['event_type'] == 'warning' + || $filter['event_type'] == 'critical' + || $filter['event_type'] == 'normal' + ) { + $sql_filters[] = ' AND event_type LIKE "%'.$filter['event_type'].'%"'; + } else if ($filter['event_type'] == 'not_normal') { + $sql_filters[] = ' AND (event_type LIKE "%warning%" + OR event_type LIKE "%critical%" + OR event_type LIKE "%unknown%")'; + } else { + $sql_filters[] = ' AND event_type = "'.$filter['event_type'].'"'; + } + } + + if (isset($filter['severity']) && $filter['severity'] > 0) { + switch ($filter['severity']) { + case EVENT_CRIT_MAINTENANCE: + case EVENT_CRIT_INFORMATIONAL: + case EVENT_CRIT_NORMAL: + case EVENT_CRIT_MINOR: + case EVENT_CRIT_WARNING: + case EVENT_CRIT_MAJOR: + case EVENT_CRIT_CRITICAL: + default: + $sql_filters[] = sprintf( + ' AND criticity = %d ', + $filter['severity'] + ); + break; + + case EVENT_CRIT_WARNING_OR_CRITICAL: + $sql_filters[] = sprintf( + ' AND (criticity = %d OR criticity = %d)', + EVENT_CRIT_WARNING, + EVENT_CRIT_CRITICAL + ); + break; + + case EVENT_CRIT_NOT_NORMAL: + $sql_filters[] = sprintf( + ' AND criticity != %d', + EVENT_CRIT_NORMAL + ); + break; + + case EVENT_CRIT_OR_NORMAL: + $sql_filters[] = sprintf( + ' AND (criticity = %d OR criticity = %d)', + EVENT_CRIT_NORMAL, + EVENT_CRIT_CRITICAL + ); + break; + } + } + + $groups = $filter['id_group_filter']; + if (isset($groups) && $groups > 0) { + $propagate = db_get_value( + 'propagate', + 'tgrupo', + 'id_grupo', + $groups + ); + + if (!$propagate) { + $sql_filters[] = sprintf( + ' AND (te.id_grupo = %d OR tasg.id_group = %d)', + $groups + ); + } else { + $children = groups_get_children($groups); + $_groups = [ $groups ]; + if (!empty($children)) { + foreach ($children as $child) { + $_groups[] = (int) $child['id_grupo']; + } + } + + $groups = $_groups; + + $sql_filters[] = sprintf( + ' AND (te.id_grupo IN (%s) OR tasg.id_group IN (%s))', + join(',', $groups), + join(',', $groups) + ); + } + } + + // Skip system messages if user is not PM. + if (!check_acl($config['id_user'], 0, 'PM')) { + $sql_filters[] = ' AND te.id_grupo != 0 '; + } + + if (isset($filter['status'])) { + switch ($filter['status']) { + case EVENT_ALL: + default: + // Do not filter. + break; + + case EVENT_NEW: + case EVENT_VALIDATE: + case EVENT_PROCESS: + $sql_filters[] = sprintf( + ' AND estado = %d', + $filter['status'] + ); + break; + + case EVENT_NO_VALIDATED: + $sql_filters[] = sprintf( + ' AND (estado = %d OR estado = %d)', + EVENT_NEW, + EVENT_PROCESS + ); + break; + } + } + + if (!$user_is_admin) { + $ER_groups = users_get_groups($config['id_user'], 'ER', false); + $EM_groups = users_get_groups($config['id_user'], 'EM', false, true); + $EW_groups = users_get_groups($config['id_user'], 'EW', false, true); + } + + if (!$user_is_admin && !users_can_manage_group_all('ER')) { + // Get groups where user have ER grants. + $sql_filters[] = sprintf( + ' AND (te.id_grupo IN ( %s ) OR tasg.id_group IN (%s))', + join(', ', array_keys($ER_groups)), + join(', ', array_keys($ER_groups)) + ); + } + + $table = events_get_events_table(is_metaconsole(), $history); + $tevento = sprintf( + ' %s te', + $table + ); + + // Prepare agent join sql filters. + $agent_join_filters = []; + $tagente_table = 'tagente'; + $tagente_field = 'id_agente'; + $conditionMetaconsole = ''; + if (is_metaconsole()) { + $tagente_table = 'tmetaconsole_agent'; + $tagente_field = 'id_tagente'; + $conditionMetaconsole = ' AND ta.id_tmetaconsole_setup = te.server_id '; + } + + // Agent alias. + if (!empty($filter['agent_alias'])) { + $agent_join_filters[] = sprintf( + ' AND ta.alias = "%s" ', + $filter['agent_alias'] + ); + } + + // Free search. + if (!empty($filter['search'])) { + if (isset($config['dbconnection']->server_version) + && $config['dbconnection']->server_version > 50600 + ) { + // Use "from_base64" requires mysql 5.6 or greater. + $custom_data_search = 'from_base64(te.custom_data)'; + } else { + // Custom data is JSON encoded base64, if 5.6 or lower, + // user is condemned to use plain search. + $custom_data_search = 'te.custom_data'; + } + + $sql_filters[] = vsprintf( + ' AND (lower(ta.alias) like lower("%%%s%%") + OR te.id_evento like "%%%s%%" + OR lower(te.evento) like lower("%%%s%%") + OR lower(te.user_comment) like lower("%%%s%%") + OR lower(te.id_extra) like lower("%%%s%%") + OR lower(te.source) like lower("%%%s%%") + OR lower('.$custom_data_search.') like lower("%%%s%%") )', + array_fill(0, 7, $filter['search']) + ); + } + + // Id extra. + if (!empty($filter['id_extra'])) { + $sql_filters[] = sprintf( + ' AND lower(te.id_extra) like lower("%%%s%%") ', + $filter['id_extra'] + ); + } + + // User comment. + if (!empty($filter['user_comment'])) { + $sql_filters[] = sprintf( + ' AND lower(te.user_comment) like lower("%%%s%%") ', + $filter['user_comment'] + ); + } + + // Source. + if (!empty($filter['source'])) { + $sql_filters[] = sprintf( + ' AND lower(te.source) like lower("%%%s%%") ', + $filter['source'] + ); + } + + // Validated or in process by. + if (!empty($filter['id_user_ack'])) { + $sql_filters[] = sprintf( + ' AND te.id_usuario like lower("%%%s%%") ', + $filter['id_user_ack'] + ); + } + + $tag_names = []; + // With following tags. + if (!empty($filter['tag_with'])) { + $tag_with = base64_decode($filter['tag_with']); + $tags = json_decode($tag_with, true); + if (is_array($tags) && !in_array('0', $tags)) { + if (!$user_is_admin) { + $user_tags = array_flip(tags_get_tags_for_module_search()); + if ($user_tags != null) { + foreach ($tags as $id_tag) { + // User cannot filter with those tags. + if (!array_search($id_tag, $user_tags)) { + return false; + } + } + } + } + + foreach ($tags as $id_tag) { + if (!isset($tags_names[$id_tag])) { + $tags_names[$id_tag] = tags_get_name($id_tag); + } + + $_tmp .= ' AND ( '; + $_tmp .= sprintf( + ' tags LIKE "%s" OR', + $tags_names[$id_tag] + ); + + $_tmp .= sprintf( + ' tags LIKE "%s,%%" OR', + $tags_names[$id_tag] + ); + + $_tmp .= sprintf( + ' tags LIKE "%%,%s" OR', + $tags_names[$id_tag] + ); + + $_tmp .= sprintf( + ' tags LIKE "%%,%s,%%" ', + $tags_names[$id_tag] + ); + + $_tmp .= ') '; + } + + $sql_filters[] = $_tmp; + } + } + + // Without following tags. + if (!empty($filter['tag_without'])) { + $tag_without = base64_decode($filter['tag_without']); + $tags = json_decode($tag_without, true); + if (is_array($tags) && !in_array('0', $tags)) { + foreach ($tags as $id_tag) { + if (!isset($tags_names[$id_tag])) { + $tags_names[$id_tag] = tags_get_name($id_tag); + } + + $_tmp .= sprintf( + ' AND tags NOT LIKE "%s" ', + $tags_names[$id_tag] + ); + $_tmp .= sprintf( + ' AND tags NOT LIKE "%s,%%" ', + $tags_names[$id_tag] + ); + $_tmp .= sprintf( + ' AND tags NOT LIKE "%%,%s" ', + $tags_names[$id_tag] + ); + $_tmp .= sprintf( + ' AND tags NOT LIKE "%%,%s,%%" ', + $tags_names[$id_tag] + ); + } + + $sql_filters[] = $_tmp; + } + } + + // Filter/ Only alerts. + if (isset($filter['filter_only_alert'])) { + if ($filter['filter_only_alert'] == 0) { + $sql_filters[] = ' AND event_type NOT LIKE "%alert%"'; + } else if ($filter['filter_only_alert'] == 1) { + $sql_filters[] = ' AND event_type LIKE "%alert%"'; + } + } + + // TAgs ACLS. + if (check_acl($config['id_user'], 0, 'ER')) { + $tags_acls_condition = tags_get_acl_tags( + // Id_user. + $config['id_user'], + // Id_group. + $ER_groups, + // Access. + 'ER', + // Return_mode. + 'event_condition', + // Query_prefix. + 'AND', + // Query_table. + '', + // Meta. + is_metaconsole(), + // Childrens_ids. + [], + // Force_group_and_tag. + true, + // Table tag for id_grupo. + 'te.', + // Alt table tag for id_grupo. + 'tasg.' + ); + // FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)". + } else if (check_acl($config['id_user'], 0, 'EW')) { + $tags_acls_condition = tags_get_acl_tags( + // Id_user. + $config['id_user'], + // Id_group. + $EW_groups, + // Access. + 'EW', + // Return_mode. + 'event_condition', + // Query_prefix. + 'AND', + // Query_table. + '', + // Meta. + is_metaconsole(), + // Childrens_ids. + [], + // Force_group_and_tag. + true, + // Table tag for id_grupo. + 'te.', + // Alt table tag for id_grupo. + 'tasg.' + ); + // FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)". + } else if (check_acl($config['id_user'], 0, 'EM')) { + $tags_acls_condition = tags_get_acl_tags( + // Id_user. + $config['id_user'], + // Id_group. + $EM_groups, + // Access. + 'EM', + // Return_mode. + 'event_condition', + // Query_prefix. + 'AND', + // Query_table. + '', + // Meta. + is_metaconsole(), + // Childrens_ids. + [], + // Force_group_and_tag. + true, + // Table tag for id_grupo. + 'te.', + // Alt table tag for id_grupo. + 'tasg.' + ); + // FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)". + } + + if (($tags_acls_condition != ERR_WRONG_PARAMETERS) + && ($tags_acls_condition != ERR_ACL) + ) { + $sql_filters[] = $tags_acls_condition; + } + + // Module search. + $agentmodule_join = 'LEFT JOIN tagente_modulo am ON te.id_agentmodule = am.id_agente_modulo'; + if (is_metaconsole()) { + $agentmodule_join = ''; + } else if (!empty($filter['module_search'])) { + $agentmodule_join = 'INNER JOIN tagente_modulo am ON te.id_agentmodule = am.id_agente_modulo'; + $sql_filters[] = sprintf( + ' AND am.nombre = "%s" ', + $filter['module_search'] + ); + } + + // Order. + $order_by = ''; + if (isset($order, $sort_field)) { + $order_by = events_get_sql_order($sort_field, $order); + } + + // Pagination. + $pagination = ''; + if (isset($limit, $offset) && $limit > 0) { + $pagination = sprintf(' LIMIT %d OFFSET %d', $limit, $offset); + } + + $extra = ''; + if (is_metaconsole()) { + $extra = ', server_id'; + } + + // Group by. + $group_by = 'GROUP BY '; + $tagente_join = 'LEFT'; + switch ($filter['group_rep']) { + case '0': + default: + // All events. + $group_by = ''; + break; + + case '1': + // Group by events. + $group_by .= 'te.estado, te.evento, te.id_agente, te.id_agentmodule'; + $group_by .= $extra; + break; + + case '2': + // Group by agents. + $tagente_join = 'INNER'; + // $group_by .= 'te.id_agente, te.event_type'; + // $group_by .= $extra; + $group_by = ''; + $order_by = events_get_sql_order('id_agente', 'asc'); + if (isset($order, $sort_field)) { + $order_by .= ','.events_get_sql_order( + $sort_field, + $order, + 0, + true + ); + } + break; + } + + $tgrupo_join = 'LEFT'; + $tgrupo_join_filters = []; + if (isset($groups) + && (is_array($groups) + || $groups > 0) + ) { + $tgrupo_join = 'INNER'; + if (is_array($groups)) { + $tgrupo_join_filters[] = sprintf( + ' AND (tg.id_grupo IN (%s) OR tasg.id_group IN (%s))', + join(', ', $groups), + join(', ', $groups) + ); + } else { + $tgrupo_join_filters[] = sprintf( + ' AND (tg.id_grupo = %s OR tasg.id_group = %s)', + $groups, + $groups + ); + } + } + + $server_join = ''; + if (is_metaconsole()) { + $server_join = ' LEFT JOIN tmetaconsole_setup ts + ON ts.id = te.server_id'; + if (!empty($filter['server_id'])) { + $server_join = sprintf( + ' INNER JOIN tmetaconsole_setup ts + ON ts.id = te.server_id AND ts.id= %d', + $filter['server_id'] + ); + } + } + + // Secondary groups. + db_process_sql('SET group_concat_max_len = 9999999'); + $event_lj = events_get_secondary_groups_left_join($table); + + $group_selects = ''; + if ($group_by != '') { + $group_selects = ',COUNT(id_evento) AS event_rep + ,GROUP_CONCAT(DISTINCT user_comment SEPARATOR "
") AS comments, + MAX(utimestamp) as timestamp_last, + MIN(utimestamp) as timestamp_first, + MAX(id_evento) as max_id_evento'; + + if ($count === false) { + $idx = array_search('te.user_comment', $fields); + if ($idx !== false) { + unset($fields[$idx]); + } + } + } + + $sql = sprintf( + 'SELECT %s + %s + FROM %s + %s + %s + %s JOIN %s ta + ON ta.%s = te.id_agente + %s + %s + %s JOIN tgrupo tg + ON te.id_grupo = tg.id_grupo + %s + %s + WHERE 1=1 + %s + %s + %s + %s + %s + ', + join(',', $fields), + $group_selects, + $tevento, + $event_lj, + $agentmodule_join, + $tagente_join, + $tagente_table, + $tagente_field, + $conditionMetaconsole, + join(' ', $agent_join_filters), + $tgrupo_join, + join(' ', $tgrupo_join_filters), + $server_join, + join(' ', $sql_filters), + $group_by, + $order_by, + $pagination, + $having + ); + + if (!$user_is_admin) { + // XXX: Confirm there's no extra grants unhandled!. + $can_manage = '0 as user_can_manage'; + if (!empty($EM_groups)) { + $can_manage = sprintf( + '(tbase.id_grupo IN (%s)) as user_can_manage', + join(', ', array_keys($EM_groups)) + ); + } + + $can_write = '0 as user_can_write'; + if (!empty($EW_groups)) { + $can_write = sprintf( + '(tbase.id_grupo IN (%s)) as user_can_write', + join(', ', array_keys($EW_groups)) + ); + } + + $sql = sprintf( + 'SELECT + tbase.*, + %s, + %s + FROM + (', + $can_manage, + $can_write + ).$sql.') tbase'; + } else { + $sql = 'SELECT + tbase.*, + 1 as user_can_manage, + 1 as user_can_write + FROM + ('.$sql.') tbase'; + } + + if ($count) { + $sql = 'SELECT count(*) as nitems FROM ('.$sql.') tt'; + } + + if ($return_sql) { + return $sql; + } + + return db_get_all_rows_sql($sql); +} + + +/** + * Get all rows of events from the database, that + * pass the filter, and can get only some fields. + * + * @param mixed $filter Filters elements. It can be an indexed array + * (keys would be the field name and value the expected + * value, and would be joined with an AND operator) or a + * string, including any SQL clause (without the WHERE + * keyword). Example: + * + * Both are similars: + * db_get_all_rows_filter ('table', ['disabled', 0]); + * db_get_all_rows_filter ('table', 'disabled = 0'); + * Both are similars: + * db_get_all_rows_filter ( + * 'table', + * [ + * 'disabled' => 0, + * 'history_data' => 0 + * ], + * 'name', + * 'OR' + * ); + * db_get_all_rows_filter ( + * 'table', + * 'disabled = 0 OR history_data = 0', 'name' + * ); + * . + * @param mixed $fields Fields of the table to retrieve. Can be an array or a + * coma separated string. All fields are retrieved by + * default. + * + * @return mixed False in case of error or invalid values passed. + * Affected rows otherwise + */ +function events_get_events($filter=false, $fields=false) +{ + if ($filter['criticity'] == EVENT_CRIT_WARNING_OR_CRITICAL) { + $filter['criticity'] = [ + EVENT_CRIT_WARNING, + EVENT_CRIT_CRITICAL, + ]; + } + + return db_get_all_rows_filter('tevento', $filter, $fields); +} + + +/** + * Get the event with the id pass as parameter. + * + * @param integer $id Event id. + * @param mixed $fields The fields to show or by default all with false. + * @param boolean $meta Metaconsole environment or not. + * @param boolean $history Retrieve also historical data. + * + * @return mixed False in case of error or invalid values passed. + * Event row otherwise. + */ +function events_get_event($id, $fields=false, $meta=false, $history=false) +{ + if (empty($id)) { + return false; + } + + global $config; + + if (is_array($fields)) { + if (! in_array('id_grupo', $fields)) { + $fields[] = 'id_grupo'; + } + } + + $table = events_get_events_table($meta, $history); + + $event = db_get_row($table, 'id_evento', $id, $fields); + if (! check_acl($config['id_user'], $event['id_grupo'], 'ER')) { + return false; + } + + return $event; +} + + +/** + * Retrieve all events ungrouped. + * + * @param string $sql_post Sql_post. + * @param integer $offset Offset. + * @param integer $pagination Pagination. + * @param boolean $meta Meta. + * @param boolean $history History. + * @param boolean $total Total. + * @param boolean $history_db History_db. + * @param string $order Order. + * + * @return mixed Array of events or false. + */ +function events_get_events_no_grouped( + $sql_post, + $offset=0, + $pagination=1, + $meta=false, + $history=false, + $total=false, + $history_db=false, + $order='ASC' +) { + global $config; + + $table = events_get_events_table($meta, $history); + + $sql = 'SELECT * FROM '.$table.' te WHERE 1=1 '.$sql_post; + + $events = db_get_all_rows_sql($sql, $history_db); + + return $events; +} + + +/** + * Return all events matching sql_post grouped. + * + * @param string $sql_post Sql_post. + * @param integer $offset Offset. + * @param integer $pagination Pagination. + * @param boolean $meta Meta. + * @param boolean $history History. + * @param boolean $total Total. + * @param boolean $history_db History_db. + * @param string $order Order. + * @param string $sort_field Sort_field. + * + * @return mixed Array of events or false. + */ +function events_get_events_grouped( + $sql_post, + $offset=0, + $pagination=1, + $meta=false, + $history=false, + $total=false, + $history_db=false, + $order='down', + $sort_field='utimestamp' +) { + global $config; + + $table = events_get_events_table($meta, $history); + + if ($meta) { + $groupby_extra = ', server_id'; + } else { + $groupby_extra = ''; + } + + db_process_sql('SET group_concat_max_len = 9999999'); + $event_lj = events_get_secondary_groups_left_join($table); + if ($total) { + $sql = "SELECT COUNT(*) FROM (SELECT id_evento + FROM $table te $event_lj + WHERE 1=1 ".$sql_post.' + GROUP BY estado, evento, id_agente, id_agentmodule'.$groupby_extra.') AS t'; + } else { + $sql = "SELECT *, MAX(id_evento) AS id_evento, + GROUP_CONCAT(DISTINCT user_comment SEPARATOR '
') AS user_comment, + GROUP_CONCAT(DISTINCT id_evento SEPARATOR ',') AS similar_ids, + COUNT(id_evento) AS event_rep, MAX(utimestamp) AS timestamp_rep, + MIN(utimestamp) AS timestamp_rep_min, + (SELECT owner_user FROM $table WHERE id_evento = MAX(te.id_evento)) owner_user, + (SELECT id_usuario FROM $table WHERE id_evento = MAX(te.id_evento)) id_usuario, + (SELECT id_agente FROM $table WHERE id_evento = MAX(te.id_evento)) id_agente, + (SELECT criticity FROM $table WHERE id_evento = MAX(te.id_evento)) AS criticity, + (SELECT ack_utimestamp FROM $table WHERE id_evento = MAX(te.id_evento)) AS ack_utimestamp, + (SELECT nombre FROM tagente_modulo WHERE id_agente_modulo = te.id_agentmodule) AS module_name + FROM $table te $event_lj + WHERE 1=1 ".$sql_post.' + GROUP BY estado, evento, id_agente, id_agentmodule'.$groupby_extra; + $sql .= ' '.events_get_sql_order($sort_field, $order, 2); + $sql .= ' LIMIT '.$offset.','.$pagination; + } + + // Extract the events by filter (or not) from db + $events = db_get_all_rows_sql($sql, $history_db); + + if ($total) { + return reset($events[0]); + } else { + return $events; + } +} + + +/** + * Return count of events grouped. + * + * @param string $sql_post Sql_post. + * @param boolean $meta Meta. + * @param boolean $history History. + * + * @return integer Number of events or false if failed. + */ +function events_get_total_events_grouped($sql_post, $meta=false, $history=false) +{ + return events_get_events_grouped($sql_post, 0, 0, $meta, $history, true); +} + + +/** + * Get all the events ids similar to a given event id. + * + * An event is similar then the event text (evento) and the id_agentmodule are + * the same. + * + * @param integer $id Event id to get similar events. + * @param boolean $meta Metaconsole mode flag. + * @param boolean $history History mode flag. + * + * @return array A list of events ids. + */ +function events_get_similar_ids($id, $meta=false, $history=false) +{ + $events_table = events_get_events_table($meta, $history); + + $ids = []; + if ($meta) { + $event = events_meta_get_event( + $id, + [ + 'evento', + 'id_agentmodule', + ], + $history + ); + } else { + $event = events_get_event($id, ['evento', 'id_agentmodule']); + } + + if ($event === false) { + return $ids; + } + + $events = db_get_all_rows_filter( + $events_table, + [ + 'evento' => $event['evento'], + 'id_agentmodule' => $event['id_agentmodule'], + ], + ['id_evento'] + ); + if ($events === false) { + return $ids; + } + + foreach ($events as $event) { + $ids[] = $event['id_evento']; + } + + return $ids; +} + + +/** + * Delete events in a transresponse + * + * @param mixed $id_event Event ID or array of events. + * @param boolean $similar Whether to delete similar events too. + * @param boolean $meta Metaconsole mode flag. + * @param boolean $history History mode flag. + * + * @return boolean Whether or not it was successful + */ +function events_delete_event( + $id_event, + $similar=true, + $meta=false, + $history=false +) { + global $config; + + $table_event = events_get_events_table($meta, $history); + + // Cleans up the selection for all unwanted values also casts any single values as an array. + $id_event = (array) safe_int($id_event, 1); + + // We must delete all events like the selected. + if ($similar) { + foreach ($id_event as $id) { + $id_event = array_merge( + $id_event, + events_get_similar_ids($id, $meta, $history) + ); + } + + $id_event = array_unique($id_event); + } + + $errors = 0; + + foreach ($id_event as $event) { + if ($meta) { + $event_group = events_meta_get_group($event, $history); + } else { + $event_group = events_get_group($event); + } + + if (check_acl($config['id_user'], $event_group, 'EM') == 0) { + // Check ACL. + db_pandora_audit('ACL Violation', 'Attempted deleting event #'.$event); + $errors++; + } else { + $ret = db_process_sql_delete($table_event, ['id_evento' => $event]); + + if (!$ret) { + $errors++; + } else { + db_pandora_audit('Event deleted', 'Deleted event #'.$event); + // ACL didn't fail nor did return. + continue; + } + } + + break; + } + + if ($errors > 0) { + return false; + } else { + return true; + } +} + + +/** + * Change the status of one or multiple events. + * + * @param mixed $id_event Event ID or array of events. + * @param integer $new_status New status of the event. + * @param boolean $meta Metaconsole mode flag. + * @param boolean $history History mode flag. + * + * @return boolean Whether or not it was successful + */ +function events_change_status( + $id_event, + $new_status, + $meta=false, + $history=false +) { + global $config; + + $event_table = events_get_events_table($meta, $history); + + // Cleans up the selection for all unwanted values also casts any single values as an array. + $id_event = (array) safe_int($id_event, 1); + + // Update ack info if the new status is validated. + if ($new_status == EVENT_STATUS_VALIDATED) { + $ack_utimestamp = time(); + $ack_user = $config['id_user']; + } else { + $acl_utimestamp = 0; + $ack_user = $config['id_user']; + } + + switch ($new_status) { + case EVENT_STATUS_NEW: + $status_string = 'New'; + break; + + case EVENT_STATUS_VALIDATED: + $status_string = 'Validated'; + break; + + case EVENT_STATUS_INPROCESS: + $status_string = 'In process'; + break; + + default: + $status_string = ''; + break; + } + + $alerts = []; + + foreach ($id_event as $k => $id) { + if ($meta) { + $event_group = events_meta_get_group($id, $history); + $event = events_meta_get_event($id, false, $history); + $server_id = $event['server_id']; + } else { + $event_group = events_get_group($id); + $event = events_get_event($id); + } + + if ($event['id_alert_am'] > 0 && !in_array($event['id_alert_am'], $alerts)) { + $alerts[] = $event['id_alert_am']; + } + + if (check_acl($config['id_user'], $event_group, 'EW') == 0) { + db_pandora_audit('ACL Violation', 'Attempted updating event #'.$id); + + unset($id_event[$k]); + } + } + + if (empty($id_event)) { + return false; + } + + $values = [ + 'estado' => $new_status, + 'id_usuario' => $ack_user, + 'ack_utimestamp' => $ack_utimestamp, + ]; + + $ret = db_process_sql_update( + $event_table, + $values, + ['id_evento' => $id_event] + ); + + if (($ret === false) || ($ret === 0)) { + return false; + } + + events_comment( + $id_event, + '', + 'Change status to '.$status_string, + $meta, + $history + ); + + if ($meta && !empty($alerts)) { + $server = metaconsole_get_connection_by_id($server_id); + metaconsole_connect($server); + } + + // Put the alerts in standby or not depends the new status. + foreach ($alerts as $alert) { + switch ($new_status) { + case EVENT_NEW: + case EVENT_VALIDATE: + alerts_agent_module_standby($alert, 0); + break; + + case EVENT_PROCESS: + alerts_agent_module_standby($alert, 1); + break; + + default: + // Ignore. + break; + } + } + + if ($meta && !empty($alerts)) { + metaconsole_restore_db(); + } + + return true; +} + + +/** + * Change the owner of an event if the event hasn't owner. + * + * @param mixed $id_event Event ID or array of events. + * @param string $new_owner Id_user of the new owner. If is false, the current + * owner will be setted. + * @param boolean $force Flag to force the change or not (not force is + * change only when it hasn't owner). + * @param boolean $meta Metaconsole mode flag. + * @param boolean $history History mode flag. + * + * @return boolean Whether or not it was successful. + */ +function events_change_owner( + $id_event, + $new_owner=false, + $force=false, + $meta=false, + $history=false +) { + global $config; + + $event_table = events_get_events_table($meta, $history); + + // Cleans up the selection for all unwanted values also casts any single + // values as an array. + $id_event = (array) safe_int($id_event, 1); + + foreach ($id_event as $k => $id) { + if ($meta) { + $event_group = events_meta_get_group($id, $history); + } else { + $event_group = events_get_group($id); + } + + if (check_acl($config['id_user'], $event_group, 'EW') == 0) { + db_pandora_audit('ACL Violation', 'Attempted updating event #'.$id); + unset($id_event[$k]); + } + } + + if (empty($id_event)) { + return false; + } + + // If no new_owner is provided, the current user will be the owner + // * #2250: Comment this lines because if possible selected None owner. + // if (empty($new_owner)) { + // $new_owner = $config['id_user']; + // } + // Only generate comment when is forced (sometimes is owner changes when + // comment). + if ($force) { + events_comment( + $id_event, + '', + 'Change owner to '.$new_owner, + $meta, + $history + ); + } + + $values = ['owner_user' => $new_owner]; + + $where = ['id_evento' => $id_event]; + + // If not force, add to where if owner_user = ''. + if (!$force) { + $where['owner_user'] = ''; + } + + $ret = db_process_sql_update( + $event_table, + $values, + $where, + 'AND', + false + ); + + if (($ret === false) || ($ret === 0)) { + return false; + } + + return true; +} + + +/** + * Returns proper event table based on environment. + * + * @param boolean $meta Metaconsole environment or not. + * @param boolean $history Historical data or not. + * + * @return string Table name. + */ +function events_get_events_table($meta, $history) +{ + if ($meta) { + if ($history) { + $event_table = 'tmetaconsole_event_history'; + } else { + $event_table = 'tmetaconsole_event'; + } + } else { + $event_table = 'tevento'; + } + + return $event_table; +} + + +/** + * Comment events in a transresponse + * + * @param mixed $id_event Event ID or array of events. + * @param string $comment Comment to be registered. + * @param string $action Action performed with comment. By default just add + * a comment. + * @param boolean $meta Flag of metaconsole mode. + * @param boolean $history Flag of history mode. + * @param boolean $similars Similars. + * + * @return boolean Whether or not it was successful + */ +function events_comment( + $id_event, + $comment='', + $action='Added comment', + $meta=false, + $history=false, + $similars=true +) { + global $config; + + $event_table = events_get_events_table($meta, $history); + + // Cleans up the selection for all unwanted values also casts any single + // values as an array. + $id_event = (array) safe_int($id_event, 1); + + foreach ($id_event as $k => $id) { + if ($meta) { + $event_group = events_meta_get_group($id, $history); + } else { + $event_group = events_get_group($id); + } + + if (check_acl($config['id_user'], $event_group, 'EW') == 0) { + db_pandora_audit('ACL Violation', 'Attempted updating event #'.$id); + + unset($id_event[$k]); + } + } + + if (empty($id_event)) { + return false; + } + + // If the event hasn't owner, assign the user as owner. + events_change_owner($id_event); + + // Get the current event comments. + $first_event = $id_event; + if (is_array($id_event)) { + $first_event = reset($id_event); + } + + $event_comments = mysql_db_process_sql( + 'SELECT user_comment FROM '.$event_table.' WHERE id_evento = '.$first_event, + 'affected_rows', + '', + false + ); + + $event_comments_array = []; + + if ($event_comments[0]['user_comment'] == '') { + $comments_format = 'new'; + } else { + // If comments are not stored in json, the format is old. + $event_comments_array = json_decode($event_comments[0]['user_comment']); + + if (empty($event_comments_array)) { + $comments_format = 'old'; + } else { + $comments_format = 'new'; + } + } + + switch ($comments_format) { + case 'new': + $comment_for_json['comment'] = $comment; + $comment_for_json['action'] = $action; + $comment_for_json['id_user'] = $config['id_user']; + $comment_for_json['utimestamp'] = time(); + + $event_comments_array[] = $comment_for_json; + + $event_comments = io_json_mb_encode($event_comments_array); + + // Update comment. + $ret = db_process_sql_update( + $event_table, + ['user_comment' => $event_comments], + ['id_evento' => implode(',', $id_event)] + ); + break; + + case 'old': + // Give old ugly format to comment. TODO: Change this method for + // aux table or json. + $comment = str_replace(["\r\n", "\r", "\n"], '
', $comment); + + if ($comment != '') { + $commentbox = '
'.$comment.'
'; + } else { + $commentbox = ''; + } + + // Don't translate 'by' word because if multiple users with + // different languages make comments in the same console + // will be a mess. + $comment = '-- '.$action.' by '.$config['id_user'].' ['.date($config['date_format']).'] --
'.$commentbox.'
'; + + // Update comment. + $sql_validation = sprintf( + 'UPDATE %s + SET user_comment = concat("%s", user_comment) + WHERE id_evento in (%s)', + $event_table, + $comment, + implode(',', $id_event) + ); + + $ret = db_process_sql($sql_validation); + break; + + default: + // Ignore. + break; + } + + if (($ret === false) || ($ret === 0)) { + return false; + } + + return true; +} + + +/** + * Get group id of an event. + * + * @param integer $id_event Event id. + * + * @return integer Group id of the given event. + */ +function events_get_group($id_event) +{ + return (int) db_get_value( + 'id_grupo', + 'tevento', + 'id_evento', + (int) $id_event + ); +} + + +/** + * Get description of an event. + * + * @param integer $id_event Event id. + * + * @return string Description of the given event. + */ +function events_get_description($id_event) +{ + return (string) db_get_value( + 'evento', + 'tevento', + 'id_evento', + (int) $id_event + ); +} + + +/** + * Insert a event in the event log system. + * + * @param integer $event Event. + * @param integer $id_group Id_group. + * @param integer $id_agent Id_agent. + * @param integer $status Status. + * @param string $id_user Id_user. + * @param string $event_type Event_type. + * @param integer $priority Priority. + * @param integer $id_agent_module Id_agent_module. + * @param integer $id_aam Id_aam. + * @param string $critical_instructions Critical_instructions. + * @param string $warning_instructions Warning_instructions. + * @param string $unknown_instructions Unknown_instructions. + * @param boolean $source Source. + * @param string $tags Tags. + * @param string $custom_data Custom_data. + * @param integer $server_id Server_id. + * @param string $id_extra Id_extra. + * + * @return integer Event id. + */ +function events_create_event( + $event, + $id_group, + $id_agent, + $status=0, + $id_user='', + $event_type='unknown', + $priority=0, + $id_agent_module=0, + $id_aam=0, + $critical_instructions='', + $warning_instructions='', + $unknown_instructions='', + $source=false, + $tags='', + $custom_data='', + $server_id=0, + $id_extra='' +) { + global $config; + + if ($source === false) { + $source = get_product_name(); + } + + $table_events = 'tevento'; + if (defined('METACONSOLE')) { + $table_events = 'tmetaconsole_event'; + + $sql = sprintf( + 'INSERT INTO '.$table_events.' (id_agente, id_grupo, evento, + timestamp, estado, utimestamp, id_usuario, + event_type, criticity, id_agentmodule, id_alert_am, + critical_instructions, warning_instructions, + unknown_instructions, source, tags, custom_data, + server_id, id_extra, data, module_status) + VALUES (%d, %d, "%s", NOW(), %d, UNIX_TIMESTAMP(NOW()), + "%s", "%s", %d, %d, %d, "%s", "%s", "%s", "%s", + "%s", "%s", %d, "%s", %d, %d)', + $id_agent, + $id_group, + $event, + $status, + $id_user, + $event_type, + $priority, + $id_agent_module, + $id_aam, + $critical_instructions, + $warning_instructions, + $unknown_instructions, + $source, + $tags, + $custom_data, + $server_id, + $id_extra, + $data, + $module_status + ); + } else { + $sql = sprintf( + 'INSERT INTO '.$table_events.' (id_agente, id_grupo, evento, + timestamp, estado, utimestamp, id_usuario, + event_type, criticity, id_agentmodule, id_alert_am, + critical_instructions, warning_instructions, + unknown_instructions, source, tags, custom_data, id_extra, data, module_status) + VALUES (%d, %d, "%s", NOW(), %d, UNIX_TIMESTAMP(NOW()), + "%s", "%s", %d, %d, %d, "%s", "%s", "%s", "%s", "%s", "%s", "%s", %d, %d)', + $id_agent, + $id_group, + $event, + $status, + $id_user, + $event_type, + $priority, + $id_agent_module, + $id_aam, + $critical_instructions, + $warning_instructions, + $unknown_instructions, + $source, + $tags, + $custom_data, + $id_extra, + $data, + $module_status + ); + } + + return (int) db_process_sql($sql, 'insert_id'); +} + + +/** + * Prints a small event table. + * + * @param string $filter SQL WHERE clause. + * @param integer $limit How many events to show. + * @param integer $width How wide the table should be. + * @param boolean $return Prints out HTML if false. + * @param integer $agent_id Agent id if is the table of one agent. + * 0 otherwise. + * @param boolean $tactical_view Be shown in tactical view or not. + * + * @return string HTML with table element. + */ +function events_print_event_table( + $filter='', + $limit=10, + $width=440, + $return=false, + $agent_id=0, + $tactical_view=false +) { + global $config; + + ui_require_css_file('events'); + + if ($agent_id == 0) { + $agent_condition = ''; + } else { + $agent_condition = ' id_agente = '.$agent_id.' AND '; + } + + if ($filter == '') { + $filter = '1 = 1'; + } + + $secondary_join = 'LEFT JOIN tagent_secondary_group tasg ON tevento.id_agente = tasg.id_agent'; + + $sql = sprintf( + 'SELECT DISTINCT tevento.* + FROM tevento %s + WHERE %s %s + ORDER BY utimestamp DESC LIMIT %d', + $secondary_join, + $agent_condition, + $filter, + $limit + ); + + $result = db_get_all_rows_sql($sql); + + if ($result === false) { + if ($return) { + $returned = ui_print_info_message(__('No events'), '', true); + return $returned; + } else { + echo ui_print_info_message(__('No events')); + } + } else { + $table = new stdClass(); + $table->id = 'latest_events_table'; + $table->cellpadding = 0; + $table->cellspacing = 0; + $table->width = $width; + $table->class = 'info_table no-td-padding'; + if (!$tactical_view) { + $table->title = __('Latest events'); + } + + $table->titleclass = 'tabletitle'; + $table->titlestyle = 'text-transform:uppercase;'; + $table->headclass = []; + $table->head = []; + $table->rowclass = []; + $table->cellclass = []; + $table->data = []; + $table->align = []; + $table->style = []; + + $i = 0; + $table->head[$i] = "".__('S.').''; + $table->headstyle[$i] = 'width: 1%;text-align: center;'; + $table->style[$i++] = 'text-align: center;'; + + $table->head[$i] = __('Type'); + $table->headstyle[$i] = 'width: 3%;text-align: center;'; + $table->style[$i++] = 'text-align: center;'; + + $table->head[$i] = __('Event name'); + $table->headstyle[$i] = ''; + $table->style[$i++] = 'word-break: break-word;'; + + if ($agent_id == 0) { + $table->head[$i] = __('Agent name'); + $table->headstyle[$i] = ''; + $table->style[$i++] = 'word-break: break-all;'; + } + + $table->head[$i] = __('Timestamp'); + $table->headstyle[$i] = 'width: 150px;'; + $table->style[$i++] = 'word-break: break-word;'; + + $table->head[$i] = __('Status'); + $table->headstyle[$i] = 'width: 150px;text-align: center;'; + $table->style[$i++] = 'text-align: center;'; + + $table->head[$i] = "".__('V.').''; + $table->headstyle[$i] = 'width: 1%;text-align: center;'; + $table->style[$i++] = 'text-align: center;'; + + $all_groups = []; + if ($agent_id != 0) { + $all_groups = agents_get_all_groups_agent($agent_id); + } + + foreach ($result as $event) { + // Copy all groups of the agent and append the event group. + $check_events = $all_groups; + $check_events[] = $event['id_grupo']; + if (! check_acl_one_of_groups($config['id_user'], $check_events, 'ER')) { + continue; + } + + $data = []; + + // Colored box. + switch ($event['estado']) { + case 0: + $img = 'images/star.png'; + $title = __('New event'); + break; + + case 1: + $img = 'images/tick.png'; + $title = __('Event validated'); + break; + + case 2: + $img = 'images/hourglass.png'; + $title = __('Event in process'); + break; + + default: + // Ignore. + break; + } + + $i = 0; + // Criticity. + $data[$i++] = ui_print_event_priority($event['criticity'], true, true); + + // Event type. + $data[$i++] = events_print_type_img($event['event_type'], true); + + // Event text. + $data[$i++] = ui_print_string_substr( + strip_tags(io_safe_output($event['evento'])), + 75, + true, + '7.5' + ); + + if ($agent_id == 0) { + if ($event['id_agente'] > 0) { + // Agent name. + // Get class name, for the link color, etc. + $data[$i] = "".agents_get_alias($event['id_agente']).''; + // For System or SNMP generated alerts. + } else if ($event['event_type'] == 'system') { + $data[$i] = __('System'); + } else { + $data[$i] = __('Alert').'SNMP'; + } + + $i++; + } + + // Timestamp. + $data[$i++] = ui_print_timestamp($event['timestamp'], true, ['style' => 'font-size: 7.5pt; letter-spacing: 0.3pt;']); + + // Status. + $data[$i++] = ui_print_event_type($event['event_type'], true); + + $data[$i++] = html_print_image( + $img, + true, + [ + 'class' => 'image_status', + 'title' => $title, + ] + ); + $table->data[] = $data; + } + + $events_table = html_print_table($table, true); + $out = $events_table; + + if (!$tactical_view) { + $out .= '
'; + if ($agent_id != 0) { + $out .= ''; + $out .= '
'; + $out .= '
+ '.__('Events -by module-').''.graph_event_module(180, 100, $event['id_agente']).'
'; + $out .= '
'; + } else { + $out .= '
'; + $out .= '
'; + $out .= '
+ '.__('Event graph').''.grafico_eventos_total('', 180, 60).'
'; + $out .= '
+ '.__('Event graph by agent').''.grafico_eventos_grupo(180, 60).'
'; + $out .= '
'; + } + + $out .= '
'; + } + + unset($table); + + if ($return) { + return $out; + } else { + echo $out; + } + } +} + + +/** + * Prints the event type image. + * + * @param string $type Event type from SQL. + * @param boolean $return Whether to return or print. + * @param boolean $only_url Flag to return only url of image, by default false. + * + * @return string HTML with img. + */ +function events_print_type_img( + $type, + $return=false, + $only_url=false +) { + global $config; + + $output = ''; + + $urlImage = ui_get_full_url(false); + + switch ($type) { + case 'alert_recovered': + $icon = 'bell.png'; + break; + + case 'alert_manual_validation': + $icon = 'ok.png'; + break; + + case 'going_down_critical': + case 'going_up_critical': + // This is to be backwards compatible. + $icon = 'module_critical.png'; + break; + + case 'going_up_normal': + case 'going_down_normal': + // This is to be backwards compatible. + $icon = 'module_ok.png'; + break; + + case 'going_up_warning': + case 'going_down_warning': + $icon = 'module_warning.png'; + break; + + case 'going_unknown': + $icon = 'module_unknown.png'; + break; + + case 'alert_fired': + $icon = 'bell_error.png'; + break; + + case 'system': + $icon = 'cog.png'; + break; + + case 'recon_host_detected': + $icon = 'recon.png'; + break; + + case 'new_agent': + $icon = 'agent.png'; + break; + + case 'configuration_change': + $icon = 'config.png'; + break; + + case 'unknown': + default: + $icon = 'lightning_go.png'; + break; + } + + if ($only_url) { + $output = $urlImage.'/images/'.$icon; + } else { + $output .= html_print_image( + 'images/'.$icon, + true, + ['title' => events_print_type_description($type, true)] + ); + } + + if ($return) { + return $output; + } + + echo $output; +} + + +/** + * Prints the event type description + * + * @param string $type Event type from SQL. + * @param boolean $return Whether to return or print. + * + * @return string HTML with img + */ +function events_print_type_description($type, $return=false) +{ + $output = ''; + + switch ($type) { + case 'going_unknown': + $output .= __('Going to unknown'); + break; + + case 'alert_recovered': + $output .= __('Alert recovered'); + break; + + case 'alert_manual_validation': + $output .= __('Alert manually validated'); + break; + + case 'going_up_warning': + $output .= __('Going from critical to warning'); + break; + + case 'going_down_critical': + case 'going_up_critical': + // This is to be backwards compatible. + $output .= __('Going up to critical state'); + break; + + case 'going_up_normal': + case 'going_down_normal': + // This is to be backwards compatible. + $output .= __('Going up to normal state'); + break; + + case 'going_down_warning': + $output .= __('Going down from normal to warning'); + break; + + case 'alert_fired': + $output .= __('Alert fired'); + break; + + case 'system'; + $output .= __('SYSTEM'); + break; + + case 'recon_host_detected'; + $output .= __('Discovery server detected a new host'); + break; + + case 'new_agent'; + $output .= __('New agent created'); + break; + + case 'configuration_change'; + $output .= __('Configuration change'); + break; + + case 'alert_ceased'; + $output .= __('Alert ceased'); + break; + + case 'error'; + $output .= __('Error'); + break; + + case 'unknown': + default: + $output .= __('Unknown type:').': '.$type; + break; + } + + if ($return) { + return $output; + } + + echo $output; +} + + +/** + * Get all the events happened in a group during a period of time. + * + * The returned events will be in the time interval ($date - $period, $date] + * + * @param mixed $begin Begin. + * @param mixed $result Result. + * @param mixed $id_group Group id to get events for. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $filter_event_validated Filter_event_validated. + * @param boolean $filter_event_critical Filter_event_critical. + * @param boolean $filter_event_warning Filter_event_warning. + * @param boolean $filter_event_no_validated Filter_event_no_validated. + * + * @return array An array with all the events happened. + */ +function events_get_group_events_steps( + $begin, + &$result, + $id_group, + $period, + $date, + $filter_event_validated=false, + $filter_event_critical=false, + $filter_event_warning=false, + $filter_event_no_validated=false +) { + global $config; + + $id_group = groups_safe_acl($config['id_user'], $id_group, 'ER'); + + if (empty($id_group)) { + // An empty array means the user doesn't have access. + return false; + } + + $datelimit = ($date - $period); + + $sql_where = ' AND 1 = 1 '; + $criticities = []; + if ($filter_event_critical) { + $criticities[] = 4; + } + + if ($filter_event_warning) { + $criticities[] = 3; + } + + if (!empty($criticities)) { + $sql_where .= ' AND criticity IN ('.implode(', ', $criticities).')'; + } + + if ($filter_event_validated) { + $sql_where .= ' AND estado = 1 '; + } + + if ($filter_event_no_validated) { + $sql_where .= ' AND estado = 0 '; + } + + $sql = sprintf( + 'SELECT *, + (SELECT t2.nombre + FROM tagente t2 + WHERE t2.id_agente = t3.id_agente) AS agent_name, + (SELECT t2.fullname + FROM tusuario t2 + WHERE t2.id_user = t3.id_usuario) AS user_name + FROM tevento t3 + WHERE utimestamp > %d AND utimestamp <= %d + AND id_grupo IN (%s) '.$sql_where.' + ORDER BY utimestamp ASC', + $datelimit, + $date, + implode(',', $id_group) + ); + + return db_get_all_row_by_steps_sql($begin, $result, $sql); +} + + +/** + * Get all the events happened in an Agent during a period of time. + * + * The returned events will be in the time interval ($date - $period, $date] + * + * @param integer $id_agent Agent id to get events. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $history History. + * @param boolean $show_summary_group Show_summary_group. + * @param boolean $filter_event_severity Filter_event_severity. + * @param boolean $filter_event_type Filter_event_type. + * @param boolean $filter_event_status Filter_event_status. + * @param boolean $filter_event_filter_search Filter_event_filter_search. + * @param boolean $id_group Id_group. + * @param boolean $events_group Events_group. + * @param boolean $id_agent_module Id_agent_module. + * @param boolean $events_module Events_module. + * @param boolean $id_server Id_server. + * + * @return array An array with all the events happened. + */ +function events_get_agent( + $id_agent, + $period, + $date=0, + $history=false, + $show_summary_group=false, + $filter_event_severity=false, + $filter_event_type=false, + $filter_event_status=false, + $filter_event_filter_search=false, + $id_group=false, + $events_group=false, + $id_agent_module=false, + $events_module=false, + $id_server=false +) { + global $config; + + if (!is_numeric($date)) { + $date = time_w_fixed_tz($date); + } + + if (is_metaconsole() && $events_group === false) { + $id_server = true; + } + + if (empty($date)) { + $date = get_system_time(); + } + + if ($events_group) { + $id_group = groups_safe_acl($config['id_user'], $id_group, 'ER'); + + if (empty($id_group)) { + // An empty array means the user doesn't have access. + return false; + } + } + + $datelimit = ($date - $period); + + $sql_where = ''; + $severity_all = 0; + if (!empty($filter_event_severity)) { + foreach ($filter_event_severity as $key => $value) { + switch ($value) { + case -1: + $severity_all = 1; + break; + + case 34: + $filter_event_severity[$key] = '3, 4'; + break; + + case 20: + $filter_event_severity[$key] = '0, 1, 3, 4, 5, 6'; + break; + + case 21: + $filter_event_severity[$key] = '4, 2'; + break; + + default: + // Ignore. + break; + } + } + + if (!$severity_all) { + $sql_where .= ' AND criticity IN ('.implode(', ', $filter_event_severity).')'; + } + } + + $status_all = 0; + if (!empty($filter_event_status)) { + foreach ($filter_event_status as $key => $value) { + switch ($value) { + case -1: + $status_all = 1; + break; + + case 3: + $filter_event_status[$key] = ('0, 2'); + default: + // Ignore. + break; + } + } + + if (!$status_all) { + $sql_where .= ' AND estado IN ('.implode( + ', ', + $filter_event_status + ).')'; + } + } + + if (!empty($filter_event_type) && $filter_event_type[0] != 'all') { + $sql_where .= ' AND ('; + $type = []; + foreach ($filter_event_type as $event_type) { + if ($event_type != '') { + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex. + // Shown to user only "warning, critical and normal". + if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { + $type[] = " event_type LIKE '%".$event_type."%' "; + } else if ($event_type == 'not_normal') { + $type[] = " (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; + } else if ($event_type != 'all') { + $type[] = " event_type = '".$event_type."'"; + } + } + } + + $sql_where .= implode(' OR ', $type).')'; + } + + if (!empty($filter_event_filter_search)) { + $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%" OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; + } + + if ($events_group) { + $sql_where .= sprintf( + ' AND id_grupo IN (%s) AND utimestamp > %d + AND utimestamp <= %d ', + implode(',', $id_group), + $datelimit, + $date + ); + } else if ($events_module) { + $sql_where .= sprintf( + ' AND id_agentmodule = %d AND utimestamp > %d + AND utimestamp <= %d ', + $id_agent_module, + $datelimit, + $date + ); + } else { + $sql_where .= sprintf( + ' AND id_agente = %d AND utimestamp > %d + AND utimestamp <= %d ', + $id_agent, + $datelimit, + $date + ); + } + + if (is_metaconsole() && $id_server) { + $sql_where .= ' AND server_id = '.$id_server; + } + + if ($show_summary_group) { + return events_get_events_grouped( + $sql_where, + 0, + 1000, + is_metaconsole(), + false, + false, + $history + ); + } else { + return events_get_events_no_grouped( + $sql_where, + 0, + 1000, + (is_metaconsole() && $id_server) ? true : false, + false, + false, + $history + ); + } +} + + +/** + * Decode a numeric type into type description. + * + * @param integer $type_id Numeric type. + * + * @return string Type description. + */ +function events_get_event_types($type_id) +{ + $diferent_types = get_event_types(); + + $type_desc = ''; + switch ($type_id) { + case 'unknown': + $type_desc = __('Unknown'); + break; + + case 'critical': + $type_desc = __('Monitor Critical'); + break; + + case 'warning': + $type_desc = __('Monitor Warning'); + break; + + case 'normal': + $type_desc = __('Monitor Normal'); + break; + + case 'alert_fired': + $type_desc = __('Alert fired'); + break; + + case 'alert_recovered': + $type_desc = __('Alert recovered'); + break; + + case 'alert_ceased': + $type_desc = __('Alert ceased'); + break; + + case 'alert_manual_validation': + $type_desc = __('Alert manual validation'); + break; + + case 'recon_host_detected': + $type_desc = __('Recon host detected'); + break; + + case 'system': + $type_desc = __('System'); + break; + + case 'error': + $type_desc = __('Error'); + break; + + case 'configuration_change': + $type_desc = __('Configuration change'); + break; + + case 'not_normal': + $type_desc = __('Not normal'); + break; + + default: + if (isset($config['text_char_long'])) { + foreach ($diferent_types as $key => $type) { + if ($key == $type_id) { + $type_desc = ui_print_truncate_text($type, $config['text_char_long'], false, true, false); + } + } + } + break; + } + + return $type_desc; +} + + +/** + * Decode a numeric severity into severity description. + * + * @param integer $severity_id Numeric severity. + * + * @return string Severity description. + */ +function events_get_severity_types($severity_id) +{ + $diferent_types = get_priorities(); + + $severity_desc = ''; + switch ($severity_id) { + case EVENT_CRIT_MAINTENANCE: + $severity_desc = __('Maintenance'); + break; + + case EVENT_CRIT_INFORMATIONAL: + $severity_desc = __('Informational'); + break; + + case EVENT_CRIT_NORMAL: + $severity_desc = __('Normal'); + break; + + case EVENT_CRIT_WARNING: + $severity_desc = __('Warning'); + break; + + case EVENT_CRIT_CRITICAL: + $severity_desc = __('Critical'); + break; + + default: + if (isset($config['text_char_long'])) { + foreach ($diferent_types as $key => $type) { + if ($key == $severity_id) { + $severity_desc = ui_print_truncate_text( + $type, + $config['text_char_long'], + false, + true, + false + ); + } + } + } + break; + } + + return $severity_desc; +} + + +/** + * Return all descriptions of event status. + * + * @param boolean $report Show in report or not. + * + * @return array Status description array. + */ +function events_get_all_status($report=false) +{ + $fields = []; + if (!$report) { + $fields[-1] = __('All event'); + $fields[0] = __('Only new'); + $fields[1] = __('Only validated'); + $fields[2] = __('Only in process'); + $fields[3] = __('Only not validated'); + } else { + $fields[-1] = __('All event'); + $fields[0] = __('New'); + $fields[1] = __('Validated'); + $fields[2] = __('In process'); + $fields[3] = __('Not Validated'); + } + + return $fields; +} + + +/** + * Decode a numeric status into status description. + * + * @param integer $status_id Numeric status. + * + * @return string Status description. + */ +function events_get_status($status_id) +{ + switch ($status_id) { + case -1: + $status_desc = __('All event'); + break; + + case 0: + $status_desc = __('Only new'); + break; + + case 1: + $status_desc = __('Only validated'); + break; + + case 2: + $status_desc = __('Only in process'); + break; + + case 3: + $status_desc = __('Only not validated'); + break; + + default: + // Ignore. + break; + } + + return $status_desc; +} + + +/** + * Checks if a user has permissions to see an event filter. + * + * @param integer $id_filter Id of the event filter. + * + * @return boolean True if the user has permissions or false otherwise. + */ +function events_check_event_filter_group($id_filter) +{ + global $config; + + $id_group = db_get_value('id_group_filter', 'tevent_filter', 'id_filter', $id_filter); + $own_info = get_user_info($config['id_user']); + // Get group list that user has access. + $groups_user = users_get_groups($config['id_user'], 'EW', $own_info['is_admin'], true); + + // Permissions in any group allow to edit "All group" filters. + if ($id_group == 0 && !empty($groups_user)) { + return true; + } + + $groups_id = []; + $has_permission = false; + + foreach ($groups_user as $key => $groups) { + if ($groups['id_grupo'] == $id_group) { + return true; + } + } + + return false; +} + + +/** + * Get a event filter. + * + * @param integer $id_filter Filter id to be fetched. + * @param array $filter Extra filter. + * @param array $fields Fields to be fetched. + * + * @return array A event filter matching id and filter or false. + */ +function events_get_event_filter($id_filter, $filter=false, $fields=false) +{ + if (empty($id_filter)) { + return false; + } + + if (! is_array($filter)) { + $filter = []; + $filter['id_filter'] = (int) $id_filter; + } + + return db_get_row_filter('tevent_filter', $filter, $fields); +} + + +/** + * Get a event filters in select format. + * + * @param boolean $manage If event filters are used for manage/view operations + * (non admin users can see group ALL for manage) # Fix. + * + * @return array A event filter matching id and filter or false. + */ +function events_get_event_filter_select($manage=true) +{ + global $config; + + $strict_acl = db_get_value('strict_acl', 'tusuario', 'id_user', $config['id_user']); + + if ($strict_acl) { + $user_groups = users_get_strict_mode_groups( + $config['id_user'], + users_can_manage_group_all() + ); + } else { + $user_groups = users_get_groups( + $config['id_user'], + 'ER', + users_can_manage_group_all(), + true + ); + } + + if (empty($user_groups)) { + return []; + } + + $sql = ' + SELECT id_filter, id_name + FROM tevent_filter + WHERE id_group_filter IN (0, '.implode(',', array_keys($user_groups)).')'; + + $event_filters = db_get_all_rows_sql($sql); + + if ($event_filters === false) { + return []; + } else { + $result = []; + foreach ($event_filters as $event_filter) { + $result[$event_filter['id_filter']] = $event_filter['id_name']; + } + } + + return $result; +} + + +/** + * Events pages functions to load modal window with advanced view of an event. + * Called from include/ajax/events.php. + * + * @param mixed $event Event. + * @param array $childrens_ids Children_ids. + * + * @return string HTML. + */ +function events_page_responses($event, $childrens_ids=[]) +{ + global $config; + // + // Responses. + // + $table_responses = new StdClass(); + $table_responses->cellspacing = 2; + $table_responses->cellpadding = 2; + $table_responses->id = 'responses_table'; + $table_responses->width = '100%'; + $table_responses->data = []; + $table_responses->head = []; + $table_responses->style[0] = 'height:30px'; + $table_responses->style[2] = 'text-align:right;'; + $table_responses->class = 'table_modal_alternate'; + + if (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EM', $event['clean_tags'], $childrens_ids)) { + // Owner. + $data = []; + $data[0] = __('Change owner'); + // Owner change can be done to users that belong to the event group + // with ER permission. + $profiles_view_events = db_get_all_rows_filter('tperfil', ['event_view' => '1'], 'id_perfil'); + foreach ($profiles_view_events as $k => $v) { + $profiles_view_events[$k] = reset($v); + } + + // Juanma (05/05/2014) Fix : Propagate ACL. + $_user_groups = array_keys( + users_get_groups($config['id_user'], 'ER', users_can_manage_group_all()) + ); + $strict_user = db_get_value( + 'strict_acl', + 'tusuario', + 'id_user', + $config['id_user'] + ); + if ($strict_user) { + $user_name = db_get_value( + 'fullname', + 'tusuario', + 'id_user', + $config['id_user'] + ); + + $users = []; + $users[0]['id_user'] = $config['id_user']; + $users[0]['fullname'] = $user_name; + } else { + $users = groups_get_users( + $_user_groups, + ['id_perfil' => $profiles_view_events], + true + ); + } + + foreach ($users as $u) { + $owners[$u['id_user']] = $u['fullname']; + } + + if ($event['owner_user'] == '') { + $owner_name = __('None'); + } else { + $owner_name = db_get_value( + 'fullname', + 'tusuario', + 'id_user', + $event['owner_user'] + ); + $owners[$event['owner_user']] = $owner_name; + } + + $data[1] = html_print_select( + $owners, + 'id_owner', + $event['owner_user'], + '', + __('None'), + -1, + true + ); + $data[2] .= html_print_button( + __('Update'), + 'owner_button', + false, + 'event_change_owner();', + 'class="sub next"', + true + ); + + $table_responses->data[] = $data; + } + + // Status. + $data = []; + $data[0] = __('Change status'); + + $status_blocked = false; + + if (tags_checks_event_acl( + $config['id_user'], + $event['id_grupo'], + 'EM', + $event['clean_tags'], + $childrens_ids + ) + ) { + // If the user has manager acls, the status can be changed to all + // possibilities always. + $status = [ + 0 => __('New'), + 2 => __('In process'), + 1 => __('Validated'), + ]; + } else { + switch ($event['estado']) { + case 0: + // If the user hasnt manager acls and the event is new. + // The status can be changed. + $status = [ + 2 => __('In process'), + 1 => __('Validated'), + ]; + break; + + case 1: + // If the user hasnt manager acls and the event is validated. + // The status cannot be changed. + $status = [1 => __('Validated')]; + $status_blocked = true; + break; + + case 2: + // If the user hasnt manager acls and the event is in process. + // The status only can be changed to validated. + $status = [1 => __('Validated')]; + break; + + default: + // Ignored. + break; + } + } + + // The change status option will be enabled only when is possible change + // the status. + $data[1] = html_print_select( + $status, + 'estado', + $event['estado'], + '', + '', + 0, + true, + false, + false, + '', + $status_blocked + ); + + if (!$status_blocked) { + $data[2] .= html_print_button( + __('Update'), + 'status_button', + false, + 'event_change_status(\''.$event['similar_ids'].'\');', + 'class="sub next"', + true + ); + } + + $table_responses->data[] = $data; + + // Comments. + $data = []; + $data[0] = __('Comment'); + $data[1] = ''; + $data[2] = html_print_button( + __('Add comment'), + 'comment_button', + false, + '$(\'#link_comments\').trigger(\'click\');', + 'class="sub next"', + true + ); + + $table_responses->data[] = $data; + + if (tags_checks_event_acl( + $config['id_user'], + $event['id_grupo'], + 'EM', + $event['clean_tags'], + $childrens_ids + ) + ) { + // Delete. + $data = []; + $data[0] = __('Delete event'); + $data[1] = ''; + $data[2] = '
'; + $data[2] .= html_print_button( + __('Delete event'), + 'delete_button', + false, + 'if(!confirm(\''.__('Are you sure?').'\')) { return false; } this.form.submit();', + 'class="sub cancel"', + true + ); + $data[2] .= html_print_input_hidden('delete', 1, true); + $data[2] .= html_print_input_hidden( + 'validate_ids', + $event['id_evento'], + true + ); + $data[2] .= '
'; + + $table_responses->data[] = $data; + } + + // Custom responses. + $data = []; + $data[0] = __('Custom responses'); + + $id_groups = array_keys(users_get_groups(false, 'EW')); + $event_responses = db_get_all_rows_filter( + 'tevent_response', + ['id_group' => $id_groups] + ); + + if (empty($event_responses)) { + $data[1] = ''.__('N/A').''; + } else { + $responses = []; + foreach ($event_responses as $v) { + $responses[$v['id']] = $v['name']; + } + + $data[1] = html_print_select( + $responses, + 'select_custom_response', + '', + '', + '', + '', + true, + false, + false + ); + + if (isset($event['server_id'])) { + $server_id = $event['server_id']; + } else { + $server_id = 0; + } + + $data[2] .= html_print_button( + __('Execute'), + 'custom_response_button', + false, + 'execute_response('.$event['id_evento'].','.$server_id.')', + "class='sub next'", + true + ); + } + + $table_responses->data[] = $data; + + $responses_js = ""; + + $responses = '
'.html_print_table($table_responses, true).$responses_js.'
'; + + return $responses; +} + + +/** + * Replace macros in the target of a response and return it. + * If server_id > 0, it's a metaconsole query. + * + * @param integer $event_id Event identifier. + * @param integer $response_id Event response identifier. + * @param integer $server_id Node identifier (for metaconsole). + * @param boolean $history Use the history database or not. + * + * @return string The response text with the macros applied. + */ +function events_get_response_target( + int $event_id, + int $response_id, + int $server_id=0, + bool $history=false +) { + global $config; + + // If server_id > 0, it's a metaconsole query. + $meta = $server_id > 0 || is_metaconsole(); + $event_table = events_get_events_table($meta, $history); + $event = db_get_row($event_table, 'id_evento', $event_id); + + $event_response = db_get_row('tevent_response', 'id', $response_id); + $target = io_safe_output($event_response['target']); + + // Substitute each macro. + if (strpos($target, '_agent_address_') !== false) { + if ($meta) { + $agente_table_name = 'tmetaconsole_agent'; + $filter = [ + 'id_tagente' => $event['id_agente'], + 'id_tmetaconsole_setup' => $server_id, + ]; + } else { + $agente_table_name = 'tagente'; + $filter = ['id_agente' => $event['id_agente']]; + } + + $ip = db_get_value_filter('direccion', $agente_table_name, $filter); + // If agent has not an IP, display N/A. + if ($ip === false) { + $ip = __('N/A'); + } + + $target = str_replace('_agent_address_', $ip, $target); + } + + if (strpos($target, '_agent_id_') !== false) { + $target = str_replace('_agent_id_', $event['id_agente'], $target); + } + + if ((strpos($target, '_module_address_') !== false) + || (strpos($target, '_module_name_') !== false) + ) { + if ($event['id_agentmodule'] !== 0) { + if ($meta) { + $server = metaconsole_get_connection_by_id($server_id); + metaconsole_connect($server); + } + + $module = db_get_row('tagente_modulo', 'id_agente_modulo', $event['id_agentmodule']); + if (empty($module['ip_target'])) { + $module['ip_target'] = __('N/A'); + } + + $target = str_replace('_module_address_', $module['ip_target'], $target); + if (empty($module['nombre'])) { + $module['nombre'] = __('N/A'); + } + + $target = str_replace( + '_module_name_', + io_safe_output($module['nombre']), + $target + ); + + if ($meta) { + metaconsole_restore_db(); + } + } else { + $target = str_replace('_module_address_', __('N/A'), $target); + $target = str_replace('_module_name_', __('N/A'), $target); + } + } + + if (strpos($target, '_event_id_') !== false) { + $target = str_replace('_event_id_', $event['id_evento'], $target); + } + + if (strpos($target, '_user_id_') !== false) { + if (!empty($event['id_usuario'])) { + $target = str_replace('_user_id_', $event['id_usuario'], $target); + } else { + $target = str_replace('_user_id_', __('N/A'), $target); + } + } + + if (strpos($target, '_group_id_') !== false) { + $target = str_replace('_group_id_', $event['id_grupo'], $target); + } + + if (strpos($target, '_group_name_') !== false) { + $target = str_replace( + '_group_name_', + groups_get_name($event['id_grupo'], true), + $target + ); + } + + if (strpos($target, '_event_utimestamp_') !== false) { + $target = str_replace( + '_event_utimestamp_', + $event['utimestamp'], + $target + ); + } + + if (strpos($target, '_event_date_') !== false) { + $target = str_replace( + '_event_date_', + date($config['date_format'], $event['utimestamp']), + $target + ); + } + + if (strpos($target, '_event_text_') !== false) { + $target = str_replace( + '_event_text_', + events_display_name($event['evento']), + $target + ); + } + + if (strpos($target, '_event_type_') !== false) { + $target = str_replace( + '_event_type_', + events_print_type_description($event['event_type'], true), + $target + ); + } + + if (strpos($target, '_alert_id_') !== false) { + $target = str_replace( + '_alert_id_', + empty($event['is_alert_am']) ? __('N/A') : $event['is_alert_am'], + $target + ); + } + + if (strpos($target, '_event_severity_id_') !== false) { + $target = str_replace('_event_severity_id_', $event['criticity'], $target); + } + + if (strpos($target, '_event_severity_text_') !== false) { + $target = str_replace( + '_event_severity_text_', + get_priority_name($event['criticity']), + $target + ); + } + + if (strpos($target, '_module_id_') !== false) { + $target = str_replace('_module_id_', $event['id_agentmodule'], $target); + } + + if (strpos($target, '_event_tags_') !== false) { + $target = str_replace('_event_tags_', $event['tags'], $target); + } + + if (strpos($target, '_event_extra_id_') !== false) { + if (empty($event['id_extra'])) { + $target = str_replace('_event_extra_id_', __('N/A'), $target); + } else { + $target = str_replace('_event_extra_id_', $event['id_extra'], $target); + } + } + + if (strpos($target, '_event_source_') !== false) { + $target = str_replace('_event_source_', $event['source'], $target); + } + + if (strpos($target, '_event_instruction_') !== false) { + $target = str_replace( + '_event_instruction_', + events_display_instructions($event['event_type'], $event, false), + $target + ); + } + + if (strpos($target, '_owner_user_') !== false) { + if (empty($event['owner_user'])) { + $target = str_replace('_owner_user_', __('N/A'), $target); + } else { + $target = str_replace('_owner_user_', $event['owner_user'], $target); + } + } + + if (strpos($target, '_event_status_') !== false) { + $event_st = events_display_status($event['estado']); + $target = str_replace('_event_status_', $event_st['title'], $target); + } + + if (strpos($target, '_group_custom_id_') !== false) { + $group_custom_id = db_get_value_sql( + sprintf( + 'SELECT custom_id FROM tgrupo WHERE id_grupo=%s', + $event['id_grupo'] + ) + ); + $event_st = events_display_status($event['estado']); + $target = str_replace('_group_custom_id_', $group_custom_id, $target); + } + + // Parse the event custom data. + if (!empty($event['custom_data'])) { + $custom_data = json_decode(base64_decode($event['custom_data'])); + foreach ($custom_data as $key => $value) { + $target = str_replace('_customdata_'.$key.'_', $value, $target); + } + } + + // This will replace the macro with the current logged user. + if (strpos($target, '_current_user_') !== false) { + $target = str_replace('_current_user_', $config['id_user'], $target); + } + + return $target; +} + + +/** + * Generates 'custom field' page for event viewer. + * + * @param array $event Event to be displayed. + * + * @return string HTML. + */ +function events_page_custom_fields($event) +{ + global $config; + + // Custom fields. + $table = new stdClass; + $table->cellspacing = 2; + $table->cellpadding = 2; + $table->width = '100%'; + $table->data = []; + $table->head = []; + $table->class = 'table_modal_alternate'; + + $all_customs_fields = (bool) check_acl( + $config['id_user'], + $event['id_grupo'], + 'AW' + ); + + if ($all_customs_fields) { + $fields = db_get_all_rows_filter('tagent_custom_fields'); + } else { + $fields = db_get_all_rows_filter( + 'tagent_custom_fields', + ['display_on_front' => 1] + ); + } + + if ($event['id_agente'] == 0) { + $fields_data = []; + } else { + $fields_data = db_get_all_rows_filter('tagent_custom_data', ['id_agent' => $event['id_agente']]); + if (is_array($fields_data)) { + $fields_data_aux = []; + foreach ($fields_data as $fd) { + $fields_data_aux[$fd['id_field']] = $fd['description']; + } + + $fields_data = $fields_data_aux; + } + } + + foreach ($fields as $field) { + // Owner. + $data = []; + $data[0] = $field['name']; + + if (empty($fields_data[$field['id_field']])) { + $data[1] = ''.__('N/A').''; + } else { + if ($field['is_password_type']) { + $data[1] = '••••••••'; + } else { + $data[1] = ui_bbcode_to_html($fields_data[$field['id_field']]); + } + } + + $field['id_field']; + + $table->data[] = $data; + } + + $custom_fields = '
'.html_print_table($table, true).'
'; + + return $custom_fields; +} + + +/** + * Retrieves extended information of given event. + * + * @param integer $id_evento Target event. + * + * @return mixed array Of extended events or false if error. + */ +function events_get_extended_events(int $id_evento) +{ + return db_get_all_rows_sql( + sprintf( + 'SELECT * FROM tevent_extended + WHERE id_evento=%d ORDER BY utimestamp DESC', + $id_evento + ) + ); + +} + + +/** + * Return if event has extended info or not. + * + * @param integer $id_event Target event. + * + * @return boolean Has extended info or not + */ +function events_has_extended_info(int $id_event) +{ + return (bool) db_get_value_sql( + sprintf( + 'SELECT count(*) as "n" FROM ( + SELECT * + FROM tevent_extended WHERE id_evento=%d LIMIT 1) t', + $id_event + ) + ); +} + + +/** + * Generates the 'related' page in event view. + * + * @param array $event To be displayed. + * @param string $server Server (if in metaconsole environment). + * + * @return string HTML to be displayed. + */ +function events_page_related($event, $server='') +{ + $html = ''; + + return $html; +} + + +/** + * Generates the 'details' page in event view. + * + * @param array $event To be displayed. + * @param string $server Server (if in metaconsole environment). + * + * @return string HTML to be displayed. + */ +function events_page_details($event, $server='') +{ + global $img_sev; + global $config; + + // If server is provided, get the hash parameters. + if (!empty($server) && is_metaconsole()) { + $hashdata = metaconsole_get_server_hashdata($server); + $hashstring = '&loginhash=auto&loginhash_data='.$hashdata.'&loginhash_user='.str_rot13($config['id_user']); + $serverstring = $server['server_url'].'/'; + + if (metaconsole_connect($server) !== NOERR) { + return ui_print_error_message(__('There was an error connecting to the node'), '', true); + } + } else { + $hashstring = ''; + $serverstring = ''; + } + + // Details. + $table_details = new stdClass; + $table_details->width = '100%'; + $table_details->data = []; + $table_details->head = []; + $table_details->cellspacing = 0; + $table_details->cellpadding = 0; + $table_details->class = 'table_modal_alternate'; + + /* + * Useless switch. + + switch ($event['event_type']) { + case 'going_unknown': + case 'going_up_warning': + case 'going_down_warning': + case 'going_up_critical': + case 'going_down_critical': + default: + // Ignore. + break; + } + */ + + if ($event['id_agente'] != 0) { + $agent = db_get_row('tagente', 'id_agente', $event['id_agente']); + } else { + $agent = []; + } + + $data[0] = __('Agent details'); + $data[1] = empty($agent) ? ''.__('N/A').'' : ''; + $table_details->data[] = $data; + + if (!empty($agent)) { + $data = []; + $data[0] = '
'.__('Name').'
'; + if (can_user_access_node()) { + $data[1] = ui_print_agent_name( + $event['id_agente'], + true, + 'agent_medium', + '', + false, + $serverstring, + $hashstring, + $agent['alias'] + ); + } else { + $data[1] = ui_print_truncate_text( + $agent['alias'], + 'agent_medium', + true, + true, + true + ); + } + + $table_details->data[] = $data; + + $data = []; + $data[0] = '
'.__('IP Address').'
'; + $data[1] = empty($agent['direccion']) ? ''.__('N/A').'' : $agent['direccion']; + $table_details->data[] = $data; + + $data = []; + $data[0] = '
'.__('OS').'
'; + $data[1] = ui_print_os_icon($agent['id_os'], true, true); + if (!empty($agent['os_version'])) { + $data[1] .= ' ('.$agent['os_version'].')'; + } + + $table_details->data[] = $data; + + $data = []; + $data[0] = '
'.__('Last contact').'
'; + $data[1] = ($agent['ultimo_contacto'] == '1970-01-01 00:00:00') ? ''.__('N/A').'' : date_w_fixed_tz($agent['ultimo_contacto']); + $table_details->data[] = $data; + + $data = []; + $data[0] = '
'.__('Last remote contact').'
'; + $data[1] = ($agent['ultimo_contacto_remoto'] == '1970-01-01 00:00:00') ? ''.__('N/A').'' : date_w_fixed_tz($agent['ultimo_contacto_remoto']); + $table_details->data[] = $data; + + $data = []; + $data[0] = '
'.__('Custom fields').'
'; + $data[1] = html_print_button( + __('View custom fields'), + 'custom_button', + false, + '$(\'#link_custom_fields\').trigger(\'click\');', + 'class="sub next"', + true + ); + $table_details->data[] = $data; + } + + if ($event['id_agentmodule'] != 0) { + $module = db_get_row_filter( + 'tagente_modulo', + [ + 'id_agente_modulo' => $event['id_agentmodule'], + 'delete_pending' => 0, + ] + ); + } else { + $module = []; + } + + $data = []; + $data[0] = __('Module details'); + $data[1] = empty($module) ? ''.__('N/A').'' : ''; + $table_details->data[] = $data; + + if (!empty($module)) { + // Module name. + $data = []; + $data[0] = '
'.__('Name').'
'; + $data[1] = $module['nombre']; + $table_details->data[] = $data; + + // Module group. + $data = []; + $data[0] = '
'.__('Module group').'
'; + $id_module_group = $module['id_module_group']; + if ($id_module_group == 0) { + $data[1] = __('No assigned'); + } else { + $module_group = db_get_value( + 'name', + 'tmodule_group', + 'id_mg', + $id_module_group + ); + $data[1] = ''; + $data[1] .= $module_group; + $data[1] .= ''; + } + + $table_details->data[] = $data; + + // ACL. + $acl_graph = false; + $strict_user = (bool) db_get_value( + 'strict_acl', + 'tusuario', + 'id_user', + $config['id_user'] + ); + + if (!empty($agent['id_grupo'])) { + $acl_graph = check_acl( + $config['id_user'], + $agent['id_grupo'], + 'RR' + ); + } + + if ($acl_graph) { + $data = []; + $data[0] = '
'.__('Graph').'
'; + + $module_type = -1; + if (isset($module['module_type'])) { + $module_type = $module['module_type']; + } + + $graph_type = return_graphtype($module_type); + $url = ui_get_full_url( + 'operation/agentes/stat_win.php', + false, + false, + false + ); + $handle = dechex( + crc32($module['id_agente_modulo'].$module['nombre']) + ); + $win_handle = 'day_'.$handle; + + $graph_params = [ + 'type' => $graph_type, + 'period' => SECONDS_1DAY, + 'id' => $module['id_agente_modulo'], + 'label' => base64_encode($module['nombre']), + 'refresh' => SECONDS_10MINUTES, + ]; + + if (defined('METACONSOLE')) { + // Set the server id. + $graph_params['server'] = $server['id']; + } + + $graph_params_str = http_build_query($graph_params); + + $link = "winopeng('".$url.'?'.$graph_params_str."','".$win_handle."')"; + + $data[1] = ''; + $data[1] .= html_print_image('images/chart_curve.png', true); + $data[1] .= ''; + $table_details->data[] = $data; + } + } + + $data = []; + $data[0] = __('Alert details'); + $data[1] = ($event['id_alert_am'] == 0) ? ''.__('N/A').'' : ''; + $table_details->data[] = $data; + + if ($event['id_alert_am'] != 0) { + $data = []; + $data[0] = '
'.__('Source').'
'; + $data[1] = ''; + $standby = db_get_value('standby', 'talert_template_modules', 'id', $event['id_alert_am']); + if (!$standby) { + $data[1] .= html_print_image( + 'images/bell.png', + true, + ['title' => __('Go to data overview')] + ); + } else { + $data[1] .= html_print_image( + 'images/bell_pause.png', + true, + ['title' => __('Go to data overview')] + ); + } + + $sql = 'SELECT name + FROM talert_templates + WHERE id IN (SELECT id_alert_template + FROM talert_template_modules + WHERE id = '.$event['id_alert_am'].');'; + + $templateName = db_get_sql($sql); + + $data[1] .= $templateName; + + $data[1] .= ''; + + $table_details->data[] = $data; + + $data = []; + $data[0] = '
'.__('Priority').'
'; + + $priority_code = db_get_value('priority', 'talert_template_modules', 'id', $event['id_alert_am']); + $alert_priority = get_priority_name($priority_code); + $data[1] = html_print_image( + $img_sev, + true, + [ + 'class' => 'image_status', + 'width' => 61, + 'height' => 28, + 'title' => $alert_priority, + 'style' => 'vertical-align:text-bottom', + ] + ); + $data[1] .= ' '.$alert_priority; + + $table_details->data[] = $data; + } + + $data = []; + $data[0] = __('Instructions'); + $data[1] = html_entity_decode(events_display_instructions($event['event_type'], $event, true)); + $table_details->data[] = $data; + + $data = []; + $data[0] = __('Extra id'); + if ($event['id_extra'] != '') { + $data[1] = $event['id_extra']; + } else { + $data[1] = ''.__('N/A').''; + } + + $table_details->data[] = $data; + + $data = []; + $data[0] = __('Source'); + if ($event['source'] != '') { + $data[1] = $event['source']; + } else { + $data[1] = ''.__('N/A').''; + } + + $table_details->data[] = $data; + + $details = '
'.html_print_table($table_details, true).'
'; + + return $details; +} + + +/** + * Generates content for 'custom data' page in event viewer. + * + * @param array $event Event. + * + * @return string HTML. + */ +function events_page_custom_data($event) +{ + global $config; + + // + // Custom data. + // + if ($event['custom_data'] == '') { + return ''; + } + + $table->width = '100%'; + $table->data = []; + $table->head = []; + $table->class = 'table_modal_alternate'; + + $json_custom_data = base64_decode($event['custom_data']); + $custom_data = json_decode($json_custom_data); + if ($custom_data === null) { + return '
'.__('Invalid custom data: %s', $json_custom_data).'
'; + } + + $i = 0; + foreach ($custom_data as $field => $value) { + $table->data[$i][0] = io_safe_output($field); + $table->data[$i][1] = io_safe_output($value); + $i++; + } + + $custom_data = '
'.html_print_table($table, true).'
'; + + return $custom_data; +} + + +/** + * Get the event name from tevento and display it in console. + * + * @param string $db_name Target event name. + * + * @return string Event name. + */ +function events_display_name($db_name='') +{ + return io_safe_output(str_replace(' ', '
', $db_name)); +} + + +/** + * Get the image and status value of event. + * + * @param integer $status Status. + * + * @return string Image path. + */ +function events_display_status($status) +{ + switch ($status) { + case 0: + return [ + 'img' => 'images/star.png', + 'title' => __('New event'), + ]; + + case 1: + return [ + 'img' => 'images/tick.png', + 'title' => __('Event validated'), + ]; + + case 2: + return [ + 'img' => 'images/hourglass.png', + 'title' => __('Event in process'), + ]; + + default: + // Ignore. + break; + } +} + + +/** + * Get the instruction of an event. + * + * @param string $event_type Type of event. + * @param array $inst Array with unknown warning and critical + * instructions. + * @param boolean $italic Display N/A between italic html marks if + * instruction is not found. + * + * @return string Safe output. + */ +function events_display_instructions($event_type='', $inst=[], $italic=true) +{ + switch ($event_type) { + case 'going_unknown': + if ($inst['unknown_instructions'] != '') { + return str_replace("\n", '
', io_safe_output($inst['unknown_instructions'])); + } + break; + + case 'going_up_warning': + case 'going_down_warning': + if ($inst['warning_instructions'] != '') { + return str_replace("\n", '
', io_safe_output($inst['warning_instructions'])); + } + break; + + case 'going_up_critical': + case 'going_down_critical': + if ($inst['critical_instructions'] != '') { + return str_replace("\n", '
', io_safe_output($inst['critical_instructions'])); + } + break; + + case 'system': + $data = []; + if ($inst['critical_instructions'] != '') { + return str_replace("\n", '
', io_safe_output($inst['critical_instructions'])); + } + + if ($inst['warning_instructions'] != '') { + return str_replace("\n", '
', io_safe_output($inst['warning_instructions'])); + } + + if ($inst['unknown_instructions'] != '') { + return str_replace("\n", '
', io_safe_output($inst['unknown_instructions'])); + } + break; + + default: + // Ignore. + break; + } + + $na_return = ($italic === true) ? ''.__('N/A').'' : __('N/A'); + + return $na_return; +} + + +/** + * Generates 'general' page for events viewer. + * + * @param array $event Event. + * + * @return string HTML. + */ +function events_page_general($event) +{ + global $img_sev; + global $config; + + /* + Commented out (old) + // $group_rep = $event['similar_ids'] == -1 ? 1 : count(explode(',',$event['similar_ids'])); + */ + + global $group_rep; + + // General. + $table_general = new stdClass; + $table_general->cellspacing = 0; + $table_general->cellpadding = 0; + $table_general->width = '100%'; + $table_general->data = []; + $table_general->head = []; + $table_general->class = 'table_modal_alternate'; + + $data = []; + $data[0] = __('Event ID'); + $data[1] = '#'.$event['id_evento']; + $table_general->data[] = $data; + + $data = []; + $data[0] = __('Event name'); + $data[1] = events_display_name($event['evento']); + $table_general->data[] = $data; + + $data = []; + $data[0] = __('Timestamp'); + + if ($group_rep == 1 && $event['event_rep'] > 1) { + $data[1] = __('First event').': '.date($config['date_format'], $event['timestamp_first']).'
'.__('Last event').': '.date($config['date_format'], $event['timestamp_last']); + } else { + $data[1] = date($config['date_format'], $event['utimestamp']); + } + + $table_general->data[] = $data; + + // $event['owner_user'] = $event['id_usuario']; + $data = []; + $data[0] = __('Owner'); + if (empty($event['owner_user'])) { + $data[1] = ''.__('N/A').''; + } else { + $user_owner = db_get_value('fullname', 'tusuario', 'id_user', $event['owner_user']); + if (empty($user_owner)) { + $user_owner = $event['owner_user']; + } + + $data[1] = $user_owner; + } + + $table_general->cellclass[3][1] = 'general_owner'; + + $table_general->data[] = $data; + + $data = []; + $data[0] = __('Type'); + $data[1] = events_print_type_description($event['event_type'], true); + $data[2] = events_print_type_img( + $event['event_type'], + true + ); + + $table_general->data[] = $data; + + $data = []; + $data[0] = __('Repeated'); + if ($group_rep != 0) { + if ($event['event_rep'] <= 1) { + $data[1] = ''.__('No').''; + } else { + $data[1] = sprintf('%d Times', $event['event_rep']); + } + } else { + $data[1] = ''.__('No').''; + } + + $table_general->data[] = $data; + + $data = []; + $data[0] = __('Severity'); + $event_criticity = get_priority_name($event['criticity']); + $data[1] = $event_criticity; + $data[2] = html_print_image( + $img_sev, + true, + [ + 'class' => 'image_status', + 'width' => 61, + 'height' => 28, + 'title' => $event_criticity, + ] + ); + $table_general->data[] = $data; + + // Get Status. + $event_st = events_display_status($event['estado']); + + $data = []; + $data[0] = __('Status'); + $data[1] = $event_st['title']; + $data[2] = html_print_image($event_st['img'], true); + $table_general->data[] = $data; + + // If event is validated, show who and when acknowleded it. + $data = []; + $data[0] = __('Acknowledged by'); + + if ($event['estado'] == 1) { + $user_ack = db_get_value('fullname', 'tusuario', 'id_user', $event['id_usuario']); + if (empty($user_ack)) { + $user_ack = $event['id_usuario']; + } + + $date_ack = date($config['date_format'], $event['ack_utimestamp']); + $data[1] = $user_ack.' ('.$date_ack.')'; + } else { + $data[1] = ''.__('N/A').''; + } + + $table_general->cellclass[7][1] = 'general_status'; + + $table_general->data[] = $data; + + $data = []; + $data[0] = __('Group'); + $data[1] = groups_get_name($event['id_grupo']); + if (!$config['show_group_name']) { + $data[2] = ui_print_group_icon($event['id_grupo'], true); + } + + $table_general->data[] = $data; + + $data = []; + $data[0] = __('Contact'); + $data[1] = ''; + $contact = db_get_value('contact', 'tgrupo', 'id_grupo', $event['id_grupo']); + if (empty($contact)) { + $data[1] = ''.__('N/A').''; + } else { + $data[1] = $contact; + } + + $table_general->data[] = $data; + + $data = []; + $data[0] = __('Tags'); + + if ($event['tags'] != '') { + $tags = tags_get_tags_formatted($event['tags']); + + $data[1] = $tags; + } else { + $data[1] = ''.__('N/A').''; + } + + $table_general->data[] = $data; + + $data = []; + $data[0] = __('ID extra'); + if ($event['id_extra'] != '') { + $data[1] = $event['id_extra']; + } else { + $data[1] = ''.__('N/A').''; + } + + $table_general->data[] = $data; + + $table_data = $table_general->data; + if (is_array($table_data)) { + $table_data_total = count($table_data); + } else { + $table_data_total = -1; + } + + for ($i = 0; $i <= $table_data_total; $i++) { + if (is_array($table_data[$i]) && count($table_data[$i]) == 2) { + $table_general->colspan[$i][1] = 2; + $table_general->style[2] = 'text-align:center; width:10%;'; + } + } + + $general = '
'.html_print_table($table_general, true).'
'; + + return $general; +} + + +/** + * Generate 'comments' page for event viewer. + * + * @param array $event Event. + * + * @return string HTML. + */ +function events_page_comments($event, $ajax=false) +{ + // Comments. + global $config; + + $comments = ''; + + $comments = $event['user_comment']; + if (isset($event['comments'])) { + $comments = explode('
', $event['comments']); + } + + $table_comments = new stdClass; + $table_comments->width = '100%'; + $table_comments->data = []; + $table_comments->head = []; + $table_comments->class = 'table_modal_alternate'; + + $comments = str_replace(["\n", ' '], '
', $comments); + + if (is_array($comments)) { + foreach ($comments as $comm) { + if (empty($comm)) { + continue; + } + + $comments_array[] = json_decode(io_safe_output($comm), true); + } + } else { + // If comments are not stored in json, the format is old. + $comments_array = json_decode(io_safe_output($comments), true); + } + + foreach ($comments_array as $comm) { + // Show the comments more recent first. + if (is_array($comm)) { + $comm = array_reverse($comm); + } + + if (empty($comm)) { + $comments_format = 'old'; + } else { + $comments_format = 'new'; + } + + switch ($comments_format) { + case 'new': + if (empty($comm)) { + $table_comments->style[0] = 'text-align:center;'; + $table_comments->colspan[0][0] = 2; + $data = []; + $data[0] = __('There are no comments'); + $table_comments->data[] = $data; + } + + if (isset($comm) === true + && is_array($comm) === true + ) { + foreach ($comm as $c) { + $data[0] = ''.$c['action'].' by '.$c['id_user'].''; + $data[0] .= '

'.date($config['date_format'], $c['utimestamp']).''; + $data[1] = $c['comment']; + $table_comments->data[] = $data; + } + } + break; + + case 'old': + $comm = explode('
', $comments); + + // Split comments and put in table. + $col = 0; + $data = []; + + foreach ($comm as $c) { + switch ($col) { + case 0: + $row_text = preg_replace('/\s*--\s*/', '', $c); + $row_text = preg_replace('/\<\/b\>/', '', $row_text); + $row_text = preg_replace('/\[/', '

[', $row_text); + $row_text = preg_replace('/[\[|\]]/', '', $row_text); + break; + + case 1: + $row_text = preg_replace("/[\r\n|\r|\n]/", '
', io_safe_output(strip_tags($c))); + break; + + default: + // Ignore. + break; + } + + $data[$col] = $row_text; + + $col++; + + if ($col == 2) { + $col = 0; + $table_comments->data[] = $data; + $data = []; + } + } + + if (count($comm) == 1 && $comm[0] == '') { + $table_comments->style[0] = 'text-align:center;'; + $table_comments->colspan[0][0] = 2; + $data = []; + $data[0] = __('There are no comments'); + $table_comments->data[] = $data; + } + break; + + default: + // Ignore. + break; + } + } + + if (((tags_checks_event_acl( + $config['id_user'], + $event['id_grupo'], + 'EM', + $event['clean_tags'], + $childrens_ids + )) || (tags_checks_event_acl( + $config['id_user'], + $event['id_grupo'], + 'EW', + $event['clean_tags'], + $childrens_ids + ))) && $config['show_events_in_local'] == false || $config['event_replication'] == false + ) { + $comments_form = '
'; + $comments_form .= html_print_textarea( + 'comment', + 3, + 10, + '', + 'style="min-height: 15px; padding:0; width: 100%; disabled"', + true + ); + + $comments_form .= '
'; + $comments_form .= html_print_button( + __('Add comment'), + 'comment_button', + false, + 'event_comment();', + 'class="sub next"', + true + ); + $comments_form .= '

'; + } else { + $comments_form = ui_print_message( + __('If event replication is ongoing, it won\'t be possible to enter comments here. This option is only to allow local pandora users to see comments, but not to operate with them. The operation, when event replication is enabled, must be done only in the Metaconsole.') + ); + } + + if ($ajax) { + return $comments_form.html_print_table($table_comments, true); + } + + return '
'.$comments_form.html_print_table($table_comments, true).'
'; +} + + +/** + * Retrieve event tags (cleaned). + * + * @param string $tags Tags. + * + * @return array of Tags. + */ +function events_clean_tags($tags) +{ + if (empty($tags)) { + return []; + } + + $event_tags = tags_get_tags_formatted($tags, false); + return explode(',', str_replace(' ', '', $event_tags)); +} + + +/** + * Get all the events happened in a group during a period of time. + * + * The returned events will be in the time interval ($date - $period, $date] + * + * @param mixed $id_group Group id to get events for. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $filter_event_severity Filter_event_severity. + * @param boolean $filter_event_type Filter_event_type. + * @param boolean $filter_event_status Filter_event_status. + * @param boolean $filter_event_filter_search Filter_event_filter_search. + * @param boolean $dbmeta Dbmeta. + * + * @return array An array with all the events happened. + */ +function events_get_count_events_by_agent( + $id_group, + $period, + $date, + $filter_event_severity=false, + $filter_event_type=false, + $filter_event_status=false, + $filter_event_filter_search=false, + $dbmeta=false +) { + global $config; + + // Date. + if (!is_numeric($date)) { + $date = time_w_fixed_tz($date); + } + + if (empty($date)) { + $date = get_system_time(); + } + + // Group. + $id_group = groups_safe_acl($config['id_user'], $id_group, 'AR'); + + if (empty($id_group)) { + // An empty array means the user doesn't have access. + return false; + } + + $datelimit = ($date - $period); + + $sql_where = ''; + $severity_all = 0; + if (!empty($filter_event_severity)) { + foreach ($filter_event_severity as $key => $value) { + switch ($value) { + case -1: + $severity_all = 1; + break; + + case 34: + $filter_event_severity[$key] = '3, 4'; + break; + + case 20: + $filter_event_severity[$key] = '0, 1, 3, 4, 5, 6'; + break; + + case 21: + $filter_event_severity[$key] = '4, 2'; + break; + + default: + // Ignore. + break; + } + } + + if (!$severity_all) { + $sql_where .= ' AND criticity IN ('.implode(', ', $filter_event_severity).')'; + } + } + + $status_all = 0; + if (!empty($filter_event_status)) { + foreach ($filter_event_status as $key => $value) { + switch ($value) { + case -1: + $status_all = 1; + break; + + case 3: + $filter_event_status[$key] = ('0, 2'); + default: + // Ignore. + break; + } + } + + if (!$status_all) { + $sql_where .= ' AND estado IN ('.implode(', ', $filter_event_status).')'; + } + } + + if (!empty($filter_event_type) && $filter_event_type[0] != 'all') { + $sql_where .= ' AND ('; + $type = []; + foreach ($filter_event_type as $event_type) { + if ($event_type != '') { + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex. + // Shown to user only "warning, critical and normal". + if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { + $type[] = " event_type LIKE '%".$event_type."%' "; + } else if ($event_type == 'not_normal') { + $type[] = " (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; + } else if ($event_type != 'all') { + $type[] = " event_type = '".$event_type."'"; + } + } + } + + $sql_where .= implode(' OR ', $type).')'; + } + + if (!empty($filter_event_filter_search)) { + $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%" OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; + } + + $tagente = 'tagente'; + $tevento = 'tevento'; + + $sql = sprintf( + 'SELECT id_agente, + (SELECT t2.alias + FROM %s t2 + WHERE t2.id_agente = t3.id_agente) AS agent_name, + COUNT(*) AS count + FROM %s t3 + WHERE utimestamp > %d AND utimestamp <= %d + AND id_grupo IN (%s) + GROUP BY id_agente', + $tagente, + $tevento, + $datelimit, + $date, + implode(',', $id_group), + $sql_where + ); + + $rows = db_get_all_rows_sql($sql); + + if ($rows == false) { + $rows = []; + } + + $return = []; + foreach ($rows as $row) { + $agent_name = $row['agent_name']; + if (empty($row['agent_name'])) { + $agent_name = __('Pandora System'); + } + + $return[$agent_name] = $row['count']; + } + + return $return; +} + + +/** + * Get all the events happened in a group during a period of time. + * + * The returned events will be in the time interval ($date - $period, $date] + * + * @param array $filter Use target filter. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $filter_event_severity Filter_event_severity. + * @param boolean $filter_event_type Filter_event_type. + * @param boolean $filter_event_status Filter_event_status. + * @param boolean $filter_event_filter_search Filter_event_filter_search. + * @param boolean $dbmeta Dbmeta. + * + * @return array An array with all the events happened. + */ +function events_get_count_events_validated_by_user( + $filter, + $period, + $date, + $filter_event_severity=false, + $filter_event_type=false, + $filter_event_status=false, + $filter_event_filter_search=false, + $dbmeta=false +) { + global $config; + // Group. + $sql_filter = ' AND 1=1 '; + if (isset($filter['id_group'])) { + $id_group = groups_safe_acl($config['id_user'], $filter['id_group'], 'AR'); + + if (empty($id_group)) { + // An empty array means the user doesn't have access. + return false; + } + + $sql_filter .= sprintf(' AND id_grupo IN (%s) ', implode(',', $id_group)); + } + + if (!empty($filter['id_agent'])) { + $sql_filter .= sprintf(' AND id_agente = %d ', $filter['id_agent']); + } + + if (!empty($filter['id_agentmodule'])) { + $sql_filter .= sprintf(' AND id_agentmodule = %d ', $filter['id_agentmodule']); + } + + // Date. + if (!is_numeric($date)) { + $date = time_w_fixed_tz($date); + } + + if (empty($date)) { + $date = get_system_time(); + } + + $datelimit = ($date - $period); + + $sql_where = ''; + $severity_all = 0; + if (!empty($filter_event_severity)) { + foreach ($filter_event_severity as $key => $value) { + switch ($value) { + case -1: + $severity_all = 1; + break; + + case 34: + $filter_event_severity[$key] = '3, 4'; + break; + + case 20: + $filter_event_severity[$key] = '0, 1, 3, 4, 5, 6'; + break; + + case 21: + $filter_event_severity[$key] = '4, 2'; + break; + + default: + // Ignore. + break; + } + } + + if (!$severity_all) { + $sql_where .= ' AND criticity IN ('.implode(', ', $filter_event_severity).')'; + } + } + + $status_all = 0; + if (!empty($filter_event_status)) { + foreach ($filter_event_status as $key => $value) { + switch ($value) { + case -1: + $status_all = 1; + break; + + case 3: + $filter_event_status[$key] = ('0, 2'); + default: + // Ignore. + break; + } + } + + if (!$status_all) { + $sql_where .= ' AND estado IN ('.implode(', ', $filter_event_status).')'; + } + } + + if (!empty($filter_event_type) && $filter_event_type[0] != 'all') { + $sql_where .= ' AND ('; + $type = []; + foreach ($filter_event_type as $event_type) { + if ($event_type != '') { + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex. + // Shown to user only "warning, critical and normal". + if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { + $type[] = " event_type LIKE '%".$event_type."%' "; + } else if ($event_type == 'not_normal') { + $type[] = " (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; + } else if ($event_type != 'all') { + $type[] = " event_type = '".$event_type."'"; + } + } + } + + $sql_where .= implode(' OR ', $type).')'; + } + + if (!empty($filter_event_filter_search)) { + $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%" OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; + } + + $tevento = 'tevento'; + + $sql = sprintf( + 'SELECT id_usuario, + (SELECT t2.fullname + FROM tusuario t2 + WHERE t2.id_user = t3.id_usuario) AS user_name, + COUNT(*) AS count + FROM %s t3 + WHERE utimestamp > %d AND utimestamp <= %d + %s %s + GROUP BY id_usuario', + $tevento, + $datelimit, + $date, + $sql_filter, + $sql_where + ); + $rows = db_get_all_rows_sql($sql); + + if ($rows == false) { + $rows = []; + } + + $return = []; + foreach ($rows as $row) { + $user_name = $row['user_name']; + if (empty($row['user_name'])) { + $user_name = __('Unknown'); + } + + $return[$user_name] = $row['count']; + } + + return $return; +} + + +/** + * Get all the events happened in a group during a period of time. + * + * The returned events will be in the time interval ($date - $period, $date] + * + * @param mixed $filter Target filter. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $filter_event_severity Filter_event_severity. + * @param boolean $filter_event_type Filter_event_type. + * @param boolean $filter_event_status Filter_event_status. + * @param boolean $filter_event_filter_search Filter_event_filter_search. + * @param boolean $dbmeta Dbmeta. + * + * @return array An array with all the events happened. + */ +function events_get_count_events_by_criticity( + $filter, + $period, + $date, + $filter_event_severity=false, + $filter_event_type=false, + $filter_event_status=false, + $filter_event_filter_search=false, + $dbmeta=false +) { + global $config; + + $sql_filter = ' AND 1=1 '; + if (isset($filter['id_group'])) { + $id_group = groups_safe_acl($config['id_user'], $filter['id_group'], 'AR'); + + if (empty($id_group)) { + // An empty array means the user doesn't have access. + return false; + } + + $sql_filter .= sprintf(' AND id_grupo IN (%s) ', implode(',', $id_group)); + } + + if (!empty($filter['id_agent'])) { + $sql_filter .= sprintf(' AND id_agente = %d ', $filter['id_agent']); + } + + if (!empty($filter['id_agentmodule'])) { + $sql_filter .= sprintf(' AND id_agentmodule = %d ', $filter['id_agentmodule']); + } + + if (!is_numeric($date)) { + $date = time_w_fixed_tz($date); + } + + if (empty($date)) { + $date = get_system_time(); + } + + $datelimit = ($date - $period); + + $sql_where = ''; + $severity_all = 0; + if (!empty($filter_event_severity)) { + foreach ($filter_event_severity as $key => $value) { + switch ($value) { + case -1: + $severity_all = 1; + break; + + case 34: + $filter_event_severity[$key] = '3, 4'; + break; + + case 20: + $filter_event_severity[$key] = '0, 1, 3, 4, 5, 6'; + break; + + case 21: + $filter_event_severity[$key] = '4, 2'; + break; + + default: + // Ignore. + break; + } + } + + if (!$severity_all) { + $sql_where .= ' AND criticity IN ('.implode(', ', $filter_event_severity).')'; + } + } + + $status_all = 0; + if (!empty($filter_event_status)) { + foreach ($filter_event_status as $key => $value) { + switch ($value) { + case -1: + $status_all = 1; + break; + + case 3: + $filter_event_status[$key] = ('0, 2'); + break; + + default: + // Ignored. + break; + } + } + + if (!$status_all) { + $sql_where .= ' AND estado IN ('.implode(', ', $filter_event_status).')'; + } + } + + if (!empty($filter_event_type) && $filter_event_type[0] != 'all') { + $sql_where .= ' AND ('; + $type = []; + foreach ($filter_event_type as $event_type) { + if ($event_type != '') { + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex. + // Shown to user only "warning, critical and normal". + if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { + $type[] = " event_type LIKE '%".$event_type."%' "; + } else if ($event_type == 'not_normal') { + $type[] = " (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; + } else if ($event_type != 'all') { + $type[] = " event_type = '".$event_type."'"; + } + } + } + + $sql_where .= implode(' OR ', $type).')'; + } + + if (!empty($filter_event_filter_search)) { + $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%" OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; + } + + $tevento = 'tevento'; + + $sql = sprintf( + 'SELECT criticity, + COUNT(*) AS count + FROM %s + WHERE utimestamp > %d AND utimestamp <= %d + %s %s + GROUP BY criticity', + $tevento, + $datelimit, + $date, + $sql_filter, + $sql_where + ); + + $rows = db_get_all_rows_sql($sql); + + if ($rows == false) { + $rows = []; + } + + $return = []; + foreach ($rows as $row) { + $return[get_priority_name($row['criticity'])] = $row['count']; + } + + return $return; +} + + +/** + * Get all the events happened in a group during a period of time. + * + * The returned events will be in the time interval ($date - $period, $date] + * + * @param mixed $filter Target filter. + * @param integer $period Period in seconds to get events. + * @param integer $date Beginning date to get events. + * @param boolean $filter_event_severity Filter_event_severity. + * @param boolean $filter_event_type Filter_event_type. + * @param boolean $filter_event_status Filter_event_status. + * @param boolean $filter_event_filter_search Filter_event_filter_search. + * @param boolean $dbmeta Dbmeta. + * + * @return array An array with all the events happened. + */ +function events_get_count_events_validated( + $filter, + $period=null, + $date=null, + $filter_event_severity=false, + $filter_event_type=false, + $filter_event_status=false, + $filter_event_filter_search=false, + $dbmeta=false +) { + global $config; + + // Group. + $sql_filter = ' 1=1 '; + if (isset($filter['id_group'])) { + $id_group = groups_safe_acl( + $config['id_user'], + $filter['id_group'], + 'AR' + ); + + if (empty($id_group)) { + // An empty array means the user doesn't have access. + return false; + } + + $sql_filter .= sprintf( + ' AND id_grupo IN (%s) ', + implode(',', $id_group) + ); + } + + // Agent. + if (!empty($filter['id_agent'])) { + $sql_filter .= sprintf( + ' AND id_agente = %d ', + $filter['id_agent'] + ); + } + + // Module. + if (!empty($filter['id_agentmodule'])) { + $sql_filter .= sprintf( + ' AND id_agentmodule = %d ', + $filter['id_agentmodule'] + ); + } + + // Date. + if (!is_numeric($date)) { + $date = time_w_fixed_tz($date); + } + + if (empty($date)) { + $date = get_system_time(); + } + + $date_filter = ''; + if (!empty($date) && !empty($period)) { + $datelimit = ($date - $period); + + $date_filter .= sprintf( + ' AND utimestamp > %d AND utimestamp <= %d ', + $datelimit, + $date + ); + } else if (!empty($period)) { + $date = time(); + $datelimit = ($date - $period); + + $date_filter .= sprintf( + ' AND utimestamp > %d AND utimestamp <= %d ', + $datelimit, + $date + ); + } else if (!empty($date)) { + $date_filter .= sprintf(' AND utimestamp <= %d ', $date); + } + + $sql_where = ''; + $severity_all = 0; + if (!empty($filter_event_severity)) { + foreach ($filter_event_severity as $key => $value) { + switch ($value) { + case -1: + $severity_all = 1; + break; + + case 34: + $filter_event_severity[$key] = '3, 4'; + break; + + case 20: + $filter_event_severity[$key] = '0, 1, 3, 4, 5, 6'; + break; + + case 21: + $filter_event_severity[$key] = '4, 2'; + break; + + default: + // Ingore. + break; + } + } + + if (!$severity_all) { + $sql_where .= ' AND criticity IN ('.implode(', ', $filter_event_severity).')'; + } + } + + $status_all = 0; + if (!empty($filter_event_status)) { + foreach ($filter_event_status as $key => $value) { + switch ($value) { + case -1: + $status_all = 1; + break; + + case 3: + $filter_event_status[$key] = ('0, 2'); + break; + + default: + // Ignore. + break; + } + } + + if (!$status_all) { + $sql_where .= ' AND estado IN ('.implode(', ', $filter_event_status).')'; + } + } + + if (!empty($filter_event_type) && $filter_event_type[0] != 'all') { + $sql_where .= ' AND ('; + $type = []; + foreach ($filter_event_type as $event_type) { + if ($event_type != '') { + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex. + // Shown to user only "warning, critical and normal". + if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { + $type[] = " event_type LIKE '%".$event_type."%' "; + } else if ($event_type == 'not_normal') { + $type[] = " (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; + } else if ($event_type != 'all') { + $type[] = " event_type = '".$event_type."'"; + } + } + } + + $sql_where .= implode(' OR ', $type).')'; + } + + if (!empty($filter_event_filter_search)) { + $sql_where .= ' AND (evento LIKE "%'.io_safe_input($filter_event_filter_search).'%" OR id_evento LIKE "%'.io_safe_input($filter_event_filter_search).'%")'; + } + + $tevento = 'tevento'; + + $sql = sprintf('SELECT estado, COUNT(*) AS count FROM %s WHERE %s %s GROUP BY estado', $tevento, $sql_filter, $sql_where); + + $rows = db_get_all_rows_sql($sql); + + if ($rows == false) { + $rows = []; + } + + $return = array_reduce( + $rows, + function ($carry, $item) { + $status = (int) $item['estado']; + $count = (int) $item['count']; + + if ($status === 1) { + $carry[__('Validated')] += $count; + } else if ($status === 0) { + $carry[__('Not validated')] += $count; + } + + return $carry; + }, + [ + __('Validated') => 0, + __('Not validated') => 0, + ] + ); + + return $return; +} + + +/** + * Check event tags. + * + * @param array $event_data Event. + * @param array $acltags Acl tags. + * + * @return boolean True or false. + */ +function events_checks_event_tags($event_data, $acltags) +{ + global $config; + + if (empty($acltags[$event_data['id_grupo']])) { + return true; + } else { + $tags_arr_acl = explode(',', $acltags[$event_data['id_grupo']]); + $tags_arr_event = explode(',', $event_data['tags']); + + foreach ($tags_arr_acl as $tag) { + $tag_name = tags_get_name($tag); + if (in_array($tag_name, $tags_arr_event)) { + return true; + } else { + $has_tag = false; + } + } + + if (!$has_tag) { + return false; + } + } + + return false; +} + + +/** + * Retrieves events grouped by agent. + * + * @param string $sql_post Sql_post. + * @param integer $offset Offset. + * @param integer $pagination Pagination. + * @param boolean $meta Meta. + * @param boolean $history History. + * @param boolean $total Total. + * + * @return array Data. + */ +function events_get_events_grouped_by_agent( + $sql_post, + $offset=0, + $pagination=1, + $meta=false, + $history=false, + $total=false +) { + global $config; + + $table = events_get_events_table($meta, $history); + + if ($meta) { + $fields_extra = ', agent_name, server_id'; + $groupby_extra = ', server_id'; + } else { + $groupby_extra = ''; + $fields_extra = ''; + } + + $event_lj = events_get_secondary_groups_left_join($table); + if ($total) { + $sql = 'SELECT COUNT(*) FROM (select id_agente from '.$table.' '.$event_lj.' WHERE 1=1 + '.$sql_post.' GROUP BY id_agente, event_type'.$groupby_extra.' ORDER BY id_agente ) AS t'; + } else { + $sql = 'select id_agente, count(*) as total'.$fields_extra.' from '.$table.' te '.$event_lj.' + WHERE id_agente > 0 '.$sql_post.' GROUP BY id_agente'.$groupby_extra.' ORDER BY id_agente LIMIT '.$offset.','.$pagination; + } + + $result = []; + // Extract the events by filter (or not) from db. + $events = db_get_all_rows_sql($sql); + $result = []; + + if ($events) { + foreach ($events as $event) { + if ($meta) { + $sql = 'SELECT event_type FROM '.$table.' te '.$event_lj." + WHERE agent_name = '".$event['agent_name']."' ".$sql_post.' ORDER BY utimestamp DESC '; + $resultado = db_get_row_sql($sql); + + $id_agente = $event['agent_name']; + $result[] = [ + 'total' => $event['total'], + 'id_server' => $event['server_id'], + 'id_agent' => $id_agente, + 'event_type' => $resultado['event_type'], + ]; + } else { + $sql = 'SELECT event_type FROM '.$table.' te '.$event_lj.' + WHERE id_agente = '.$event['id_agente'].' '.$sql_post.' ORDER BY utimestamp DESC '; + $resultado = db_get_row_sql($sql); + + $id_agente = $event['id_agente']; + $result[] = [ + 'total' => $event['total'], + 'id_agent' => $id_agente, + 'event_type' => $resultado['event_type'], + ]; + } + } + } + + return $result; +} + + +/** + * Return SQL query to group events by agents. + * + * @param mixed $id_agent Id_agent. + * @param integer $server_id Server_id. + * @param string $event_type Event_type. + * @param integer $severity Severity. + * @param integer $status Status. + * @param string $search Search. + * @param integer $id_agent_module Id_agent_module. + * @param integer $event_view_hr Event_view_hr. + * @param boolean $id_user_ack Id_user_ack. + * @param array $tag_with Tag_with. + * @param array $tag_without Tag_without. + * @param boolean $filter_only_alert Filter_only_alert. + * @param string $date_from Date_from. + * @param string $date_to Date_to. + * @param boolean $id_user Id_user. + * @param boolean $server_id_search Server_id_search. + * + * @return string SQL. + */ +function events_sql_events_grouped_agents( + $id_agent, + $server_id=-1, + $event_type='', + $severity=-1, + $status=3, + $search='', + $id_agent_module=0, + $event_view_hr=8, + $id_user_ack=false, + $tag_with=[], + $tag_without=[], + $filter_only_alert=false, + $date_from='', + $date_to='', + $id_user=false, + $server_id_search=false +) { + global $config; + + $sql_post = ' 1 = 1 '; + + $meta = false; + if (is_metaconsole()) { + $meta = true; + } + + switch ($status) { + case 0: + case 1: + case 2: + $sql_post .= ' AND estado = '.$status; + break; + + case 3: + $sql_post .= ' AND (estado = 0 OR estado = 2)'; + break; + + default: + // Ignore. + break; + } + + if ($search != '') { + $sql_post .= " AND (evento LIKE '%".io_safe_input($search)."%' OR id_evento LIKE '%".$search."%')"; + } + + if ($event_type != '') { + // If normal, warning, could be several (going_up_warning, going_down_warning... too complex + // Shown to user only "warning, critical and normal". + if ($event_type == 'warning' || $event_type == 'critical' || $event_type == 'normal') { + $sql_post .= " AND event_type LIKE '%".$event_type."%' "; + } else if ($event_type == 'not_normal') { + $sql_post .= " AND (event_type LIKE '%warning%' OR event_type LIKE '%critical%' OR event_type LIKE '%unknown%') "; + } else if ($event_type != 'all') { + $sql_post .= " AND event_type = '".$event_type."'"; + } + } + + if ($severity != -1) { + switch ($severity) { + case EVENT_CRIT_WARNING_OR_CRITICAL: + $sql_post .= ' + AND (criticity = '.EVENT_CRIT_WARNING.' OR + criticity = '.EVENT_CRIT_CRITICAL.')'; + break; + + case EVENT_CRIT_OR_NORMAL: + $sql_post .= ' + AND (criticity = '.EVENT_CRIT_NORMAL.' OR + criticity = '.EVENT_CRIT_CRITICAL.')'; + break; + + case EVENT_CRIT_NOT_NORMAL: + $sql_post .= ' AND criticity != '.EVENT_CRIT_NORMAL; + break; + + default: + $sql_post .= ' AND criticity = '.$severity; + break; + } + } + + // In metaconsole mode the agent search is performed by name. + if ($meta) { + if ($id_agent != __('All')) { + $sql_post .= " AND agent_name LIKE '%".$id_agent."%'"; + } + } else { + switch ($id_agent) { + case 0: + // Ignore. + $__invalid_value = 1; + break; + + case -1: + // Agent doesnt exist. No results will returned. + $sql_post .= ' AND 1 = 0'; + break; + + default: + $sql_post .= ' AND id_agente = '.$id_agent; + break; + } + } + + // There is another filter for if ($meta). + if (!$meta) { + if (!empty($text_module)) { + $sql_post .= " AND id_agentmodule IN ( + SELECT id_agente_modulo + FROM tagente_modulo + WHERE nombre = '".$text_module."' + )"; + } + } + + if ($id_user_ack != '0') { + $sql_post .= " AND id_usuario = '".$id_user_ack."'"; + } + + if (!isset($date_from)) { + $date_from = ''; + } + + if (!isset($date_to)) { + $date_to = ''; + } + + if (($date_from == '') && ($date_to == '')) { + if ($event_view_hr > 0) { + $unixtime = (get_system_time() - ($event_view_hr * SECONDS_1HOUR)); + $sql_post .= ' AND (utimestamp > '.$unixtime.')'; + } + } else { + if ($date_from != '') { + $udate_from = strtotime($date_from.' 00:00:00'); + $sql_post .= ' AND (utimestamp >= '.$udate_from.')'; + } + + if ($date_to != '') { + $udate_to = strtotime($date_to.' 23:59:59'); + $sql_post .= ' AND (utimestamp <= '.$udate_to.')'; + } + } + + // Search by tag. + if (!empty($tag_with) && (io_safe_output($tag_with) != '[]') && (io_safe_output($tag_with) != '["0"]')) { + $sql_post .= ' AND ( '; + $first = true; + foreach ($tag_with as $id_tag) { + if ($first) { + $first = false; + } else { + $sql_post .= ' OR '; + } + + $sql_post .= "tags = '".tags_get_name($id_tag)."'"; + } + + $sql_post .= ' ) '; + } + + if (!empty($tag_without) && (io_safe_output($tag_without) != '[]') && (io_safe_output($tag_with) != '["0"]')) { + $sql_post .= ' AND ( '; + $first = true; + foreach ($tag_without as $id_tag) { + if ($first) { + $first = false; + } else { + $sql_post .= ' AND '; + } + + $sql_post .= "tags <> '".tags_get_name($id_tag)."'"; + } + + $sql_post .= ' ) '; + } + + // Filter/Only alerts. + if (isset($filter_only_alert)) { + if ($filter_only_alert == 0) { + $sql_post .= " AND event_type NOT LIKE '%alert%'"; + } else if ($filter_only_alert == 1) { + $sql_post .= " AND event_type LIKE '%alert%'"; + } + } + + // Tags ACLS. + if ($id_group > 0 && in_array($id_group, array_keys($groups))) { + $group_array = (array) $id_group; + } else { + $group_array = array_keys($groups); + } + + $tags_acls_condition = tags_get_acl_tags( + $id_user, + $group_array, + 'ER', + 'event_condition', + 'AND', + '', + $meta, + [], + true + ); + // FORCE CHECK SQL "(TAG = tag1 AND id_grupo = 1)". + if (($tags_acls_condition != ERR_WRONG_PARAMETERS) && ($tags_acls_condition != ERR_ACL) && ($tags_acls_condition != -110000)) { + $sql_post .= $tags_acls_condition; + } + + // Metaconsole filters. + if ($meta) { + if ($server_id_search) { + $sql_post .= ' AND server_id = '.$server_id_search; + } else { + $enabled_nodes = db_get_all_rows_sql( + ' + SELECT id + FROM tmetaconsole_setup + WHERE disabled = 0' + ); + + if (empty($enabled_nodes)) { + $sql_post .= ' AND 1 = 0'; + } else { + if ($strict_user == 1) { + $enabled_nodes_id = []; + } else { + $enabled_nodes_id = [0]; + } + + foreach ($enabled_nodes as $en) { + $enabled_nodes_id[] = $en['id']; + } + + $sql_post .= ' AND server_id IN ('.implode(',', $enabled_nodes_id).')'; + } + } + } + + return $sql_post; +} + + +/** + * Retrieve list of events grouped by agents. + * + * @param string $sql SQL. + * + * @return string HTML. + */ +function events_list_events_grouped_agents($sql) +{ + global $config; + + $table = events_get_events_table(is_metaconsole(), $history); + + $sql = sprintf( + 'SELECT * FROM %s + LEFT JOIN tagent_secondary_group + ON tagent_secondary_group.id_agent = id_agente + WHERE %s', + $table, + $sql + ); + + $result = db_get_all_rows_sql($sql); + $group_rep = 0; + $meta = is_metaconsole(); + + // Fields that the user has selected to show. + if ($meta) { + $show_fields = events_meta_get_custom_fields_user(); + } else { + $show_fields = explode(',', $config['event_fields']); + } + + // Headers. + $i = 0; + $table = new stdClass(); + if (!isset($table->width)) { + $table->width = '100%'; + } + + $table->id = 'eventtable'; + $table->cellpadding = 4; + $table->cellspacing = 4; + if (!isset($table->class)) { + $table->class = 'databox data'; + } + + $table->head = []; + $table->data = []; + + $table->head[$i] = __('ID'); + $table->align[$i] = 'left'; + $i++; + if (in_array('server_name', $show_fields)) { + $table->head[$i] = __('Server'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('estado', $show_fields)) { + $table->head[$i] = __('Status'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('id_evento', $show_fields)) { + $table->head[$i] = __('Event ID'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('evento', $show_fields)) { + $table->head[$i] = __('Event Name'); + $table->align[$i] = 'left'; + $table->style[$i] = 'min-width: 200px; max-width: 350px; word-break: break-all;'; + $i++; + } + + if (in_array('id_agente', $show_fields)) { + $table->head[$i] = __('Agent name'); + $table->align[$i] = 'left'; + $table->style[$i] = 'max-width: 350px; word-break: break-all;'; + $i++; + } + + if (in_array('timestamp', $show_fields)) { + $table->head[$i] = __('Timestamp'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('id_usuario', $show_fields)) { + $table->head[$i] = __('User'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('owner_user', $show_fields)) { + $table->head[$i] = __('Owner'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('id_grupo', $show_fields)) { + $table->head[$i] = __('Group'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('event_type', $show_fields)) { + $table->head[$i] = __('Event type'); + $table->align[$i] = 'left'; + $table->style[$i] = 'min-width: 85px;'; + $i++; + } + + if (in_array('id_agentmodule', $show_fields)) { + $table->head[$i] = __('Agent Module'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('id_alert_am', $show_fields)) { + $table->head[$i] = __('Alert'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('criticity', $show_fields)) { + $table->head[$i] = __('Severity'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('user_comment', $show_fields)) { + $table->head[$i] = __('Comment'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('tags', $show_fields)) { + $table->head[$i] = __('Tags'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('source', $show_fields)) { + $table->head[$i] = __('Source'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('id_extra', $show_fields)) { + $table->head[$i] = __('Extra ID'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('ack_utimestamp', $show_fields)) { + $table->head[$i] = __('ACK Timestamp'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('instructions', $show_fields)) { + $table->head[$i] = __('Instructions'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('data', $show_fields)) { + $table->head[$i] = __('Data'); + $table->align[$i] = 'left'; + $i++; + } + + if (in_array('module_status', $show_fields)) { + $table->head[$i] = __('Module status'); + $table->align[$i] = 'left'; + $i++; + } + + if ($i != 0 && $allow_action) { + $table->head[$i] = __('Action'); + $table->align[$i] = 'left'; + $table->size[$i] = '90px'; + $i++; + if (check_acl($config['id_user'], 0, 'EW') == 1 && !$readonly) { + $table->head[$i] = html_print_checkbox('all_validate_box', '1', false, true); + $table->align[$i] = 'left'; + } + } + + if ($meta) { + // Get info of the all servers to use it on hash auth. + $servers_url_hash = metaconsole_get_servers_url_hash(); + $servers = metaconsole_get_servers(); + } + + $show_delete_button = false; + $show_validate_button = false; + + $idx = 0; + // Arrange data. We already did ACL's in the query. + foreach ($result as $event) { + $data = []; + + if ($meta) { + $event['server_url_hash'] = $servers_url_hash[$event['server_id']]; + $event['server_url'] = $servers[$event['server_id']]['server_url']; + $event['server_name'] = $servers[$event['server_id']]['server_name']; + } + + // Clean url from events and store in array. + $event['clean_tags'] = events_clean_tags($event['tags']); + + // First pass along the class of this row. + $myclass = get_priority_class($event['criticity']); + + // Print status. + $estado = $event['estado']; + + // Colored box. + switch ($estado) { + case EVENT_NEW: + $img_st = 'images/star.png'; + $title_st = __('New event'); + break; + + case EVENT_VALIDATE: + $img_st = 'images/tick.png'; + $title_st = __('Event validated'); + break; + + case EVENT_PROCESS: + $img_st = 'images/hourglass.png'; + $title_st = __('Event in process'); + break; + + default: + // Ignore. + break; + } + + $i = 0; + + $data[$i] = '#'.$event['id_evento']; + $table->cellstyle[count($table->data)][$i] = 'background: #F3F3F3; color: #111 !important;'; + + // Pass grouped values in hidden fields to use it from modal window. + if ($group_rep) { + $similar_ids = $event['similar_ids']; + $timestamp_first = $event['timestamp_rep_min']; + $timestamp_last = $event['timestamp_rep']; + } else { + $similar_ids = $event['id_evento']; + $timestamp_first = $event['utimestamp']; + $timestamp_last = $event['utimestamp']; + } + + // Store group data to show in extended view. + $data[$i] .= html_print_input_hidden('similar_ids_'.$event['id_evento'], $similar_ids, true); + $data[$i] .= html_print_input_hidden('timestamp_first_'.$event['id_evento'], $timestamp_first, true); + $data[$i] .= html_print_input_hidden('timestamp_last_'.$event['id_evento'], $timestamp_last, true); + $data[$i] .= html_print_input_hidden('childrens_ids', json_encode($childrens_ids), true); + + // Store server id if is metaconsole. 0 otherwise. + if ($meta) { + $server_id = $event['server_id']; + + // If meta activated, propagate the id of the event on node (source id). + $data[$i] .= html_print_input_hidden('source_id_'.$event['id_evento'], $event['id_source_event'], true); + $table->cellclass[count($table->data)][$i] = $myclass; + } else { + $server_id = 0; + } + + $data[$i] .= html_print_input_hidden('server_id_'.$event['id_evento'], $server_id, true); + + if (empty($event['event_rep'])) { + $event['event_rep'] = 0; + } + + $data[$i] .= html_print_input_hidden('event_rep_'.$event['id_evento'], $event['event_rep'], true); + // Store concat comments to show in extended view. + $data[$i] .= html_print_input_hidden('user_comment_'.$event['id_evento'], base64_encode($event['user_comment']), true); + + $i++; + + if (in_array('server_name', $show_fields)) { + if ($meta) { + if (can_user_access_node()) { + $data[$i] = "".$event['server_name'].''; + } else { + $data[$i] = $event['server_name']; + } + } else { + $data[$i] = db_get_value('name', 'tserver'); + } + + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('estado', $show_fields)) { + $data[$i] = html_print_image( + $img_st, + true, + [ + 'class' => 'image_status', + 'title' => $title_st, + 'id' => 'status_img_'.$event['id_evento'], + ] + ); + $table->cellstyle[count($table->data)][$i] = 'background: #F3F3F3;'; + $i++; + } + + if (in_array('id_evento', $show_fields)) { + $data[$i] = $event['id_evento']; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + switch ($event['criticity']) { + default: + case 0: + $img_sev = 'images/status_sets/default/severity_maintenance.png'; + break; + case 1: + $img_sev = 'images/status_sets/default/severity_informational.png'; + break; + + case 2: + $img_sev = 'images/status_sets/default/severity_normal.png'; + break; + + case 3: + $img_sev = 'images/status_sets/default/severity_warning.png'; + break; + + case 4: + $img_sev = 'images/status_sets/default/severity_critical.png'; + break; + + case 5: + $img_sev = 'images/status_sets/default/severity_minor.png'; + break; + + case 6: + $img_sev = 'images/status_sets/default/severity_major.png'; + break; + } + + if (in_array('evento', $show_fields)) { + // Event description. + $data[$i] = ''; + if ($allow_action) { + $data[$i] .= ''; + } + + $data[$i] .= ''.ui_print_truncate_text(io_safe_output($event['evento']), 160).''; + if ($allow_action) { + $data[$i] .= ''; + } + + $data[$i] .= ''; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('id_agente', $show_fields)) { + $data[$i] = ''; + + if ($event['id_agente'] > 0) { + // Agent name. + if ($meta) { + $agent_link = ''; + if (can_user_access_node()) { + $data[$i] = ''.$agent_link.$event['agent_name'].''; + } else { + $data[$i] = $event['agent_name']; + } + } else { + $data[$i] .= ui_print_agent_name($event['id_agente'], true); + } + } else { + $data[$i] .= ''; + } + + $data[$i] .= ''; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('timestamp', $show_fields)) { + // Time. + $data[$i] = ''; + if ($group_rep == 1) { + $data[$i] .= ui_print_timestamp($event['timestamp_rep'], true); + } else { + $data[$i] .= ui_print_timestamp($event['timestamp'], true); + } + + $data[$i] .= ''; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('id_usuario', $show_fields)) { + $user_name = db_get_value('fullname', 'tusuario', 'id_user', $event['id_usuario']); + if (empty($user_name)) { + $user_name = $event['id_usuario']; + } + + $data[$i] = $user_name; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('owner_user', $show_fields)) { + $owner_name = db_get_value('fullname', 'tusuario', 'id_user', $event['owner_user']); + if (empty($owner_name)) { + $owner_name = $event['owner_user']; + } + + $data[$i] = $owner_name; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('id_grupo', $show_fields)) { + if ($meta) { + $data[$i] = $event['group_name']; + } else { + $id_group = $event['id_grupo']; + $group_name = db_get_value('nombre', 'tgrupo', 'id_grupo', $id_group); + if ($id_group == 0) { + $group_name = __('All'); + } + + $data[$i] = $group_name; + } + + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('event_type', $show_fields)) { + $data[$i] = events_print_type_description($event['event_type'], true); + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('id_agentmodule', $show_fields)) { + if ($meta) { + $module_link = ''; + if (can_user_access_node()) { + $data[$i] = ''.$module_link.$event['module_name'].''; + } else { + $data[$i] = $event['module_name']; + } + } else { + $module_name = db_get_value('nombre', 'tagente_modulo', 'id_agente_modulo', $event['id_agentmodule']); + $data[$i] = ''.$module_name.''; + } + + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('id_alert_am', $show_fields)) { + if ($meta) { + $data[$i] = $event['alert_template_name']; + } else { + if ($event['id_alert_am'] != 0) { + $sql = 'SELECT name + FROM talert_templates + WHERE id IN (SELECT id_alert_template + FROM talert_template_modules + WHERE id = '.$event['id_alert_am'].');'; + + $templateName = db_get_sql($sql); + $data[$i] = ''.$templateName.''; + } else { + $data[$i] = ''; + } + } + + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('criticity', $show_fields)) { + $data[$i] = get_priority_name($event['criticity']); + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('user_comment', $show_fields)) { + $safe_event_user_comment = strip_tags(io_safe_output($event['user_comment'])); + $line_breaks = [ + "\r\n", + "\n", + "\r", + ]; + $safe_event_user_comment = str_replace($line_breaks, '
', $safe_event_user_comment); + $event_user_comments = json_decode($safe_event_user_comment, true); + $event_user_comment_str = ''; + + if (!empty($event_user_comments)) { + $last_key = key(array_slice($event_user_comments, -1, 1, true)); + $date_format = $config['date_format']; + + foreach ($event_user_comments as $key => $event_user_comment) { + $event_user_comment_str .= sprintf( + '%s: %s
%s: %s
%s: %s
', + __('Date'), + date($date_format, $event_user_comment['utimestamp']), + __('User'), + $event_user_comment['id_user'], + __('Comment'), + $event_user_comment['comment'] + ); + if ($key != $last_key) { + $event_user_comment_str .= '
'; + } + } + } + + $comments_help_tip = ''; + if (!empty($event_user_comment_str)) { + $comments_help_tip = ui_print_help_tip($event_user_comment_str, true); + } + + $data[$i] = ''.$comments_help_tip.''; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('tags', $show_fields)) { + $data[$i] = tags_get_tags_formatted($event['tags']); + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('source', $show_fields)) { + $data[$i] = $event['source']; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('id_extra', $show_fields)) { + $data[$i] = $event['id_extra']; + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('ack_utimestamp', $show_fields)) { + if ($event['ack_utimestamp'] == 0) { + $data[$i] = ''; + } else { + $data[$i] = date($config['date_format'], $event['ack_utimestamp']); + } + + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('instructions', $show_fields)) { + switch ($event['event_type']) { + case 'going_unknown': + if (!empty($event['unknown_instructions'])) { + $data[$i] = html_print_image('images/page_white_text.png', true, ['title' => str_replace("\n", '
', io_safe_output($event['unknown_instructions']))]); + } + break; + + case 'going_up_critical': + case 'going_down_critical': + if (!empty($event['critical_instructions'])) { + $data[$i] = html_print_image('images/page_white_text.png', true, ['title' => str_replace("\n", '
', io_safe_output($event['critical_instructions']))]); + } + break; + + case 'going_down_warning': + if (!empty($event['warning_instructions'])) { + $data[$i] = html_print_image('images/page_white_text.png', true, ['title' => str_replace("\n", '
', io_safe_output($event['warning_instructions']))]); + } + break; + + case 'system': + if (!empty($event['critical_instructions'])) { + $data[$i] = html_print_image('images/page_white_text.png', true, ['title' => str_replace("\n", '
', io_safe_output($event['critical_instructions']))]); + } else if (!empty($event['warning_instructions'])) { + $data[$i] = html_print_image('images/page_white_text.png', true, ['title' => str_replace("\n", '
', io_safe_output($event['warning_instructions']))]); + } else if (!empty($event['unknown_instructions'])) { + $data[$i] = html_print_image('images/page_white_text.png', true, ['title' => str_replace("\n", '
', io_safe_output($event['unknown_instructions']))]); + } + break; + + default: + // Ignore. + break; + } + + if (!isset($data[$i])) { + $data[$i] = ''; + } + + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('data', $show_fields)) { + $data[$i] = $event['data']; + if (($data[$i] % 1) == 0) { + $data[$i] = number_format($data[$i], 0); + } else { + $data[$i] = number_format($data[$i], 2); + } + + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if (in_array('module_status', $show_fields)) { + $data[$i] = modules_get_modules_status($event['module_status']); + $table->cellclass[count($table->data)][$i] = $myclass; + $i++; + } + + if ($i != 0 && $allow_action) { + // Actions. + $data[$i] = ''; + + if (!$readonly) { + // Validate event. + if (($event['estado'] != 1) && (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EW', $event['clean_tags'], $childrens_ids))) { + $show_validate_button = true; + $data[$i] .= ''; + $data[$i] .= html_print_image( + 'images/ok.png', + true, + ['title' => __('Validate event')] + ); + $data[$i] .= ''; + } + + // Delete event. + if ((tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EM', $event['clean_tags'], $childrens_ids) == 1)) { + if ($event['estado'] != 2) { + $show_delete_button = true; + $data[$i] .= ''; + $data[$i] .= html_print_image( + 'images/cross.png', + true, + [ + 'title' => __('Delete event'), + 'id' => 'delete_cross_'.$event['id_evento'], + ] + ); + $data[$i] .= ''; + } else { + $data[$i] .= html_print_image( + 'images/cross.disabled.png', + true, + ['title' => __('Is not allowed delete events in process')] + ).' '; + } + } + } + + $data[$i] .= ''; + $data[$i] .= html_print_input_hidden('event_title_'.$event['id_evento'], '#'.$event['id_evento'].' - '.$event['evento'], true); + $data[$i] .= html_print_image( + 'images/eye.png', + true, + ['title' => __('Show more')] + ); + $data[$i] .= ''; + + $table->cellstyle[count($table->data)][$i] = 'background: #F3F3F3;'; + + $i++; + + if (!$readonly) { + if (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EM', $event['clean_tags'], $childrens_ids) == 1) { + // Checkbox. + // Class 'candeleted' must be the fist class to be parsed from javascript. Dont change. + $data[$i] = html_print_checkbox_extended('validate_ids[]', $event['id_evento'], false, false, false, 'class="candeleted chk_val"', true); + } else if (tags_checks_event_acl($config['id_user'], $event['id_grupo'], 'EW', $event['clean_tags'], $childrens_ids) == 1) { + // Checkbox. + $data[$i] = html_print_checkbox_extended('validate_ids[]', $event['id_evento'], false, false, false, 'class="chk_val"', true); + } else if (isset($table->header[$i]) || true) { + $data[$i] = ''; + } + } + + $table->cellstyle[count($table->data)][$i] = 'background: #F3F3F3;'; + } + + array_push($table->data, $data); + + $idx++; + } + + return html_print_table($table, true); +} + + +/** + * Retrieves SQL for custom order. + * + * @param string $sort_field Field. + * @param string $sort Order. + * @param integer $group_rep Group field. + * @param boolean $only-fields Return only fields. + * + * @return string SQL. + */ +function events_get_sql_order($sort_field='timestamp', $sort='DESC', $group_rep=0, $only_fields=false) +{ + $sort_field_translated = $sort_field; + switch ($sort_field) { + case 'event_id': + $sort_field_translated = 'id_evento'; + break; + + case 'event_name': + $sort_field_translated = 'evento'; + break; + + case 'status': + $sort_field_translated = 'estado'; + break; + + case 'agent_id': + $sort_field_translated = 'id_agente'; + break; + + case 'timestamp': + $sort_field_translated = ($group_rep == 0) ? 'timestamp' : 'timestamp_rep'; + break; + + case 'user_id': + $sort_field_translated = 'id_usuario'; + break; + + case 'owner': + $sort_field_translated = 'owner_user'; + break; + + case 'group_id': + $sort_field_translated = 'id_grupo'; + break; + + case 'alert_id': + $sort_field_translated = 'id_alert_am'; + break; + + case 'comment': + $sort_field_translated = 'user_comment'; + break; + + case 'extra_id': + $sort_field_translated = 'id_extra'; + break; + + default: + $sort_field_translated = $sort_field; + break; + } + + if (strtolower($sort) != 'asc' && strtolower($sort) != 'desc') { + $dir = ($sort == 'up') ? 'ASC' : 'DESC'; + } else { + $dir = $sort; + } + + if ($only_fields) { + return $sort_field_translated.' '.$dir; + } + + return 'ORDER BY '.$sort_field_translated.' '.$dir; +} + + +/** + * SQL left join of event queries to handle secondary groups. + * + * @param string $table Table to use based on environment. + * + * @return string With the query. + */ +function events_get_secondary_groups_left_join($table) +{ + if ($table == 'tevento') { + return 'LEFT JOIN tagent_secondary_group tasg ON te.id_agente = tasg.id_agent'; + } + + return 'LEFT JOIN tmetaconsole_agent_secondary_group tasg + ON te.id_agente = tasg.id_tagente AND te.server_id = tasg.id_tmetaconsole_setup'; +} + + +<<<<<<< HEAD +function events_get_instructions($event) +{ + if (!is_array($event)) { + return ''; + } + + switch ($event['event_type']) { + case 'going_unknown': + if ($event['unknown_instructions'] != '') { + $value = str_replace("\n", '
', io_safe_output($event['unknown_instructions'])); + } + break; + + case 'going_up_warning': + case 'going_down_warning': + if ($event['warning_instructions'] != '') { + $value = str_replace("\n", '
', io_safe_output($event['warning_instructions'])); + } + break; + + case 'going_up_critical': + case 'going_down_critical': + if ($event['critical_instructions'] != '') { + $value = str_replace("\n", '
', io_safe_output($event['critical_instructions'])); + } + break; + } + + if (!isset($value)) { + return ''; + } + + $max_text_length = 300; + $over_text = io_safe_output($value); + if (strlen($over_text) > ($max_text_length + 3)) { + $over_text = substr($over_text, 0, $max_text_length).'...'; + } + + $output = '
'; + $output .= ''; + $output .= ''; + $output .= html_print_image('images/default_list.png', true, ['title' => $over_text]).''; + $output .= ''; + + return $output; +======= +/** + * Replace macros in any string given an event id. + * If server_id > 0, it's a metaconsole query. + * + * @param integer $event_id Event identifier. + * @param integer $value String value in which we want to apply macros. + * + * @return string The response text with the macros applied. + */ +function events_get_field_value_by_event_id( + int $event_id, + $value +) { + global $config; + + $meta = false; + $event = db_get_row('tevento', 'id_evento', $event_id); + + // Replace each macro. + if (strpos($value, '_agent_address_') !== false) { + if ($meta) { + $agente_table_name = 'tmetaconsole_agent'; + $filter = [ + 'id_tagente' => $event['id_agente'], + 'id_tmetaconsole_setup' => $server_id, + ]; + } else { + $agente_table_name = 'tagente'; + $filter = ['id_agente' => $event['id_agente']]; + } + + $ip = db_get_value_filter('direccion', $agente_table_name, $filter); + // If agent does not have an IP, display N/A. + if ($ip === false) { + $ip = __('N/A'); + } + + $value = str_replace('_agent_address_', $ip, $value); + } + + if (strpos($value, '_agent_id_') !== false) { + $value = str_replace('_agent_id_', $event['id_agente'], $value); + } + + if (strpos($value, '_module_address_') !== false) { + if ($event['id_agentmodule'] != 0) { + if ($meta) { + $server = metaconsole_get_connection_by_id($server_id); + metaconsole_connect($server); + } + + $module = db_get_row('tagente_modulo', 'id_agente_modulo', $event['id_agentmodule']); + if (empty($module['ip_target'])) { + $module['ip_target'] = __('N/A'); + } + + $value = str_replace('_module_address_', $module['ip_target'], $value); + if (empty($module['nombre'])) { + $module['nombre'] = __('N/A'); + } + + if ($meta) { + metaconsole_restore_db(); + } + } else { + $value = str_replace('_module_address_', __('N/A'), $value); + } + } + + if (strpos($value, '_module_name_') !== false) { + if ($event['id_agentmodule'] != 0) { + if ($meta) { + $server = metaconsole_get_connection_by_id($server_id); + metaconsole_connect($server); + } + + $module = db_get_row('tagente_modulo', 'id_agente_modulo', $event['id_agentmodule']); + if (empty($module['ip_target'])) { + $module['ip_target'] = __('N/A'); + } + + $value = str_replace( + '_module_name_', + io_safe_output($module['nombre']), + $value + ); + + if ($meta) { + metaconsole_restore_db(); + } + } else { + $value = str_replace('_module_name_', __('N/A'), $value); + } + } + + if (strpos($value, '_event_id_') !== false) { + $value = str_replace('_event_id_', $event['id_evento'], $value); + } + + if (strpos($value, '_user_id_') !== false) { + if (!empty($event['id_usuario'])) { + $value = str_replace('_user_id_', $event['id_usuario'], $value); + } else { + $value = str_replace('_user_id_', __('N/A'), $value); + } + } + + if (strpos($value, '_group_id_') !== false) { + $value = str_replace('_group_id_', $event['id_grupo'], $value); + } + + if (strpos($value, '_group_name_') !== false) { + $value = str_replace( + '_group_name_', + groups_get_name($event['id_grupo'], true), + $value + ); + } + + if (strpos($value, '_event_utimestamp_') !== false) { + $value = str_replace( + '_event_utimestamp_', + $event['utimestamp'], + $value + ); + } + + if (strpos($value, '_event_date_') !== false) { + $value = str_replace( + '_event_date_', + date($config['date_format'], $event['utimestamp']), + $value + ); + } + + if (strpos($value, '_event_text_') !== false) { + $value = str_replace( + '_event_text_', + events_display_name($event['evento']), + $value + ); + } + + if (strpos($value, '_event_type_') !== false) { + $value = str_replace( + '_event_type_', + events_print_type_description($event['event_type'], true), + $value + ); + } + + if (strpos($value, '_alert_id_') !== false) { + $value = str_replace( + '_alert_id_', + empty($event['is_alert_am']) ? __('N/A') : $event['is_alert_am'], + $value + ); + } + + if (strpos($value, '_event_severity_id_') !== false) { + $value = str_replace('_event_severity_id_', $event['criticity'], $value); + } + + if (strpos($value, '_event_severity_text_') !== false) { + $value = str_replace( + '_event_severity_text_', + get_priority_name($event['criticity']), + $value + ); + } + + if (strpos($value, '_module_id_') !== false) { + $value = str_replace('_module_id_', $event['id_agentmodule'], $value); + } + + if (strpos($value, '_event_tags_') !== false) { + $value = str_replace('_event_tags_', $event['tags'], $value); + } + + if (strpos($value, '_event_extra_id_') !== false) { + if (empty($event['id_extra'])) { + $value = str_replace('_event_extra_id_', __('N/A'), $value); + } else { + $value = str_replace('_event_extra_id_', $event['id_extra'], $value); + } + } + + if (strpos($value, '_event_source_') !== false) { + $value = str_replace('_event_source_', $event['source'], $value); + } + + if (strpos($value, '_event_instruction_') !== false) { + $value = str_replace( + '_event_instruction_', + events_display_instructions($event['event_type'], $event, false), + $value + ); + } + + if (strpos($value, '_owner_user_') !== false) { + if (empty($event['owner_user'])) { + $value = str_replace('_owner_user_', __('N/A'), $value); + } else { + $value = str_replace('_owner_user_', $event['owner_user'], $value); + } + } + + if (strpos($value, '_event_status_') !== false) { + $event_st = events_display_status($event['estado']); + $value = str_replace('_event_status_', $event_st['title'], $value); + } + + if (strpos($value, '_group_custom_id_') !== false) { + $group_custom_id = db_get_value_sql( + sprintf( + 'SELECT custom_id FROM tgrupo WHERE id_grupo=%s', + $event['id_grupo'] + ) + ); + $event_st = events_display_status($event['estado']); + $value = str_replace('_group_custom_id_', $group_custom_id, $value); + } + + // Parse the event custom data. + if (!empty($event['custom_data'])) { + $custom_data = json_decode(base64_decode($event['custom_data'])); + foreach ($custom_data as $key => $val) { + $value = str_replace('_customdata_'.$key.'_', $val, $value); + } + } + + // This will replace the macro with the current logged user. + if (strpos($value, '_current_user_') !== false) { + $value = str_replace('_current_user_', $config['id_user'], $value); + } + + return $value; + +>>>>>>> origin/develop +} diff --git a/pandora_console/include/functions_graph.php b/pandora_console/include/functions_graph.php index d0e844c3bf..cddd447673 100644 --- a/pandora_console/include/functions_graph.php +++ b/pandora_console/include/functions_graph.php @@ -295,12 +295,41 @@ function grafico_modulo_sparse_data( return false; } - $array_data['sum'.$series_suffix]['agent_module_id'] = $agent_module_id; - $array_data['sum'.$series_suffix]['id_module_type'] = $data_module_graph['id_module_type']; - $array_data['sum'.$series_suffix]['agent_name'] = $data_module_graph['agent_name']; - $array_data['sum'.$series_suffix]['module_name'] = $data_module_graph['module_name']; - $array_data['sum'.$series_suffix]['agent_alias'] = $data_module_graph['agent_alias']; - $array_data['sum'.$series_suffix]['unit'] = $data_module_graph['unit']; + $array_data = series_suffix_leyend( + 'sum', + $series_suffix, + $agent_module_id, + $data_module_graph, + $array_data + ); + + if ($params['percentil']) { + $array_data = series_suffix_leyend( + 'percentil', + $series_suffix, + $agent_module_id, + $data_module_graph, + $array_data + ); + } + + if ($params['type_mode_graph']) { + $array_data = series_suffix_leyend( + 'min', + $series_suffix, + $agent_module_id, + $data_module_graph, + $array_data + ); + + $array_data = series_suffix_leyend( + 'max', + $series_suffix, + $agent_module_id, + $data_module_graph, + $array_data + ); + } // This is for a specific type of report that consists in passing // an interval and doing the average sum and avg. @@ -378,12 +407,6 @@ function grafico_modulo_sparse_data( $array_data['sum1']['data'] = $acum_array_data; } - if ($params['percentil']) { - $percentil_value = $array_data['percentil'.$series_suffix]['data'][0][1]; - } else { - $percentil_value = 0; - } - $events = []; if (isset($array_data['sum'.$series_suffix]['max'])) { $max = $array_data['sum'.$series_suffix]['max']; @@ -1471,8 +1494,6 @@ function graphic_combined_module( $min = $array_data['sum'.$i]['min']; $avg = $array_data['sum'.$i]['avg']; - $percentil_value = $array_data['percentil'.$i]['data'][0][1]; - if ($config['fixed_graph'] == false) { $water_mark = [ 'file' => $config['homedir'].'/images/logo_vertical_water.png', @@ -1521,7 +1542,8 @@ function graphic_combined_module( $array_data, $params_combined['average'], $params_combined['summatory'], - $params_combined['modules_series'] + $params_combined['modules_series'], + $date_array ); } } @@ -2222,7 +2244,7 @@ function graphic_combined_module( * @param boolean $average Average. * @param boolean $summatory Summatory. * @param boolean $modules_series Series module. - * @param boolean $baseline Baseline data. + * @param array $date_array Date data. * * @return array Data. */ @@ -2231,106 +2253,82 @@ function combined_graph_summatory_average( $average=false, $summatory=false, $modules_series=false, - $baseline=false + $date_array=[] ) { if (isset($array_data) && is_array($array_data)) { + $reduce_array = []; foreach ($array_data as $key => $value) { if (strpos($key, 'sum') !== false) { - $data_array_reverse[$key] = array_reverse($value['data']); - if (!$modules_series) { - unset($array_data[$key]); - } + $last = $date_array['start_date']; + $reduce_array = array_reduce( + $value['data'], + function ($carry, $item) use ($date_array, $last, $reduce_array) { + $slice_start = $date_array['start_date']; + $iterator = $last; + + // JS to PHP timestamp format. + $item[0] /= 1000; + while ($iterator <= $date_array['final_date']) { + if ($item[0] >= $slice_start && $item[0] < $iterator) { + $array = []; + $val = 0; + $n = 0; + + if (is_array($reduce_array[$slice_start])) { + $val = $reduce_array[$slice_start]['value']; + $n = ($reduce_array[$slice_start]['n'] + 1); + } + + $array['value'] = ($item[1] + $val); + $array['n'] = $n; + $array['t'] = ($slice_start * 1000); + + $carry[$slice_start] = $array; + $last = $iterator; + break; + } else { + $slice_start = $iterator; + $iterator += 300; + } + } + + $i++; + return $carry; + }, + $reduce_array + ); + } + + if (!$modules_series) { + unset($array_data[$key]); } } - if (isset($data_array_reverse) && is_array($data_array_reverse)) { - $array_sum_reverse = []; - $array_avg_reverse = []; - $data_array_prev = false; - $data_array_pop = []; - $count = 0; + $reduce_array_summatory = []; + $reduce_array_average = []; + $i = 0; + foreach ($reduce_array as $item) { + $reduce_array_summatory[$i][0] = $item['t']; + $reduce_array_summatory[$i][1] = $item['value']; - $count_data_array_reverse = count($data_array_reverse['sum0']); - while ($count_data_array_reverse > 0) { - foreach ($data_array_reverse as $key_reverse => $value_reverse) { - if (is_array($value_reverse) && count($value_reverse) > 0) { - $data_array_pop[$key_reverse] = array_pop( - $data_array_reverse[$key_reverse] - ); - } - } + $reduce_array_average[$i][0] = $item['t']; + $reduce_array_average[$i][1] = ($item['value'] / ($item['n'] + 1)); - if (isset($data_array_pop) && is_array($data_array_pop)) { - $acum_data = 0; - $acum_array = []; - $sum_data = 0; - $count_pop = 0; - foreach ($data_array_pop as $key_pop => $value_pop) { - if ($value_pop[0] > $acum_data) { - if ($acum_data != 0) { - $sum_data = ($sum_data + $data_array_prev[$key_pop][1]); - $data_array_reverse[$key_pop][] = $value_pop; - $data_array_prev[$acum_key] = $acum_array; - } else { - if ($data_array_prev[$key_pop] == false) { - $data_array_prev[$key_pop] = $value_pop; - } + $i++; + } - $acum_key = $key_pop; - $acum_data = $value_pop[0]; - $acum_array = $value_pop; - $sum_data = $value_pop[1]; - } - } else if ($value_pop[0] < $acum_data) { - $sum_data = ($sum_data + $data_array_prev[$key_pop][1]); - $data_array_reverse[$acum_key][] = $acum_array; - $data_array_prev[$key_pop] = $value_pop; - $acum_key = $key_pop; - $acum_data = $value_pop[0]; - $acum_array = $value_pop; - } else if ($value_pop[0] == $acum_data) { - $data_array_prev[$key_pop] = $value_pop; - $sum_data += $value_pop[1]; - } + if ($summatory && isset($reduce_array_summatory) + && is_array($reduce_array_summatory) + && count($reduce_array_summatory) > 0 + ) { + $array_data['summatory']['data'] = $reduce_array_summatory; + } - $count_pop++; - } - - if ($summatory) { - $array_sum_reverse[$count][0] = $acum_data; - $array_sum_reverse[$count][1] = $sum_data; - } - - if ($average) { - $array_avg_reverse[$count][0] = $acum_data; - $array_avg_reverse[$count][1] = ($sum_data / $count_pop); - } - } - - $count++; - $count_data_array_reverse--; - } - - if ($summatory && isset($array_sum_reverse) - && is_array($array_sum_reverse) - && count($array_sum_reverse) > 0 - ) { - $array_data['summatory']['data'] = $array_sum_reverse; - $array_data['summatory']['color'] = 'purple'; - } - - if ($average && isset($array_avg_reverse) - && is_array($array_avg_reverse) - && count($array_avg_reverse) > 0 - ) { - if ($baseline) { - $array_data['baseline']['data'] = $array_avg_reverse; - $array_data['baseline']['color'] = 'green'; - } else { - $array_data['average']['data'] = $array_avg_reverse; - $array_data['average']['color'] = 'orange'; - } - } + if ($average && isset($reduce_array_average) + && is_array($reduce_array_average) + && count($reduce_array_average) > 0 + ) { + $array_data['average']['data'] = $reduce_array_average; } return $array_data; @@ -3191,6 +3189,21 @@ function graphic_incident_source($width=320, $height=200) } +function series_suffix_leyend($series_name, $series_suffix, $id_agent, $data_module_graph, $array_data) +{ + global $config; + + $array_data[$series_name.$series_suffix]['agent_module_id'] = $id_agent; + $array_data[$series_name.$series_suffix]['id_module_type'] = $data_module_graph['id_module_type']; + $array_data[$series_name.$series_suffix]['agent_name'] = $data_module_graph['agent_name']; + $array_data[$series_name.$series_suffix]['module_name'] = $data_module_graph['module_name']; + $array_data[$series_name.$series_suffix]['agent_alias'] = $data_module_graph['agent_alias']; + $array_data[$series_name.$series_suffix]['unit'] = $data_module_graph['unit']; + + return $array_data; +} + + function graph_events_validated($width=300, $height=200, $extra_filters=[], $meta=false, $history=false) { global $config; @@ -3582,7 +3595,32 @@ function graph_custom_sql_graph( $SQL_GRAPH_MAX_LABEL_SIZE = 20; + if (is_metaconsole()) { + $server = metaconsole_get_connection_names(); + $connection = metaconsole_get_connection($server); + metaconsole_connect($connection); + } + $report_content = db_get_row('treport_content', 'id_rc', $id); + + if ($report_content == false || $report_content == '') { + $report_content = db_get_row('treport_content_template', 'id_rc', $id); + } + + if ($report_content == false || $report_content == '') { + enterprise_hook('metaconsole_restore_db'); + $report_content = db_get_row('treport_content', 'id_rc', $id); + if ($report_content == false || $report_content == '') { + $report_content = db_get_row('treport_content_template', 'id_rc', $id); + } + + if (is_metaconsole()) { + $server = metaconsole_get_connection_names(); + $connection = metaconsole_get_connection($server); + metaconsole_connect($connection); + } + } + if ($id != null) { $historical_db = db_get_value_sql('SELECT historical_db from treport_content where id_rc ='.$id); } else { @@ -3596,22 +3634,9 @@ function graph_custom_sql_graph( $sql = io_safe_output($sql['sql']); } - if (($config['metaconsole'] == 1) && defined('METACONSOLE')) { - $metaconsole_connection = enterprise_hook('metaconsole_get_connection', [$report_content['server_name']]); - - if ($metaconsole_connection === false) { - return false; - } - - if (enterprise_hook('metaconsole_load_external_db', [$metaconsole_connection]) != NOERR) { - // ui_print_error_message ("Error connecting to ".$server_name); - return false; - } - } - $data_result = db_get_all_rows_sql($sql, $historical_db); - if (($config['metaconsole'] == 1) && defined('METACONSOLE')) { + if (is_metaconsole()) { enterprise_hook('metaconsole_restore_db'); } diff --git a/pandora_console/include/functions_html.php b/pandora_console/include/functions_html.php index 08d60dbb6e..ab3aad9c7a 100644 --- a/pandora_console/include/functions_html.php +++ b/pandora_console/include/functions_html.php @@ -98,6 +98,23 @@ function hd($var, $file='', $oneline=false) } +/** + * Encapsulation (ob) for debug print function. + * + * @param mixed $var Variable to be dumped. + * @param string $file Target file path. + * @param boolean $oneline Show in oneline. + * + * @return string Dump string. + */ +function obhd($var, $file='', $oneline=false) +{ + ob_start(); + hd($var, $file, $oneline); + return ob_get_clean(); +} + + function debug() { $args_num = func_num_args(); @@ -1458,6 +1475,14 @@ function html_print_input_password( $attr['class'] = $class; } + if ($disabled === false) { + // Trick to avoid password completion on most browsers. + if ($autocomplete !== 'on') { + $disabled = true; + $attr['onfocus'] = "this.removeAttribute('readonly');"; + } + } + return html_print_input_text_extended($name, $value, 'password-'.$name, $alt, $size, $maxlength, $disabled, '', $attr, $return, true, '', $autocomplete); } @@ -1570,6 +1595,7 @@ function html_print_input_image($name, $src, $value, $style='', $return=false, $ 'onkeypress', 'onkeydown', 'onkeyup', + 'class', ]; foreach ($attrs as $attribute) { @@ -3152,7 +3178,8 @@ function html_print_input($data, $wrapper='div', $input_only=false) ((isset($data['return']) === true) ? $data['return'] : false), ((isset($data['disabled']) === true) ? $data['disabled'] : false), ((isset($data['required']) === true) ? $data['required'] : false), - ((isset($data['class']) === true) ? $data['class'] : '') + ((isset($data['class']) === true) ? $data['class'] : ''), + ((isset($data['autocomplete']) === true) ? $data['autocomplete'] : 'off') ); break; @@ -3356,3 +3383,116 @@ function html_print_input($data, $wrapper='div', $input_only=false) return $output; } + + +/** + * Print an autocomplete input filled out with Integria IMS users. + * + * @param string $name The name of ajax control, by default is "users". + * @param string $default The default value to show in the ajax control. + * @param boolean $return If it is true return a string with the output instead to echo the output. + * @param string $size Size. + * + * @return mixed If the $return is true, return the output as string. + */ +function html_print_autocomplete_users_from_integria( + $name='users', + $default='', + $return=false, + $size='30', + $disable=false, + $required=false +) { + global $config; + + ob_start(); + + $attrs = ['style' => 'background: url(images/user_green.png) no-repeat right;']; + + if ($required) { + $attrs['required'] = 'required'; + } + + html_print_input_text_extended( + $name, + $default, + 'text-'.$name, + '', + $size, + 100, + $disable, + '', + $attrs + ); + html_print_input_hidden($name.'_hidden', $id_agent_module); + + ui_print_help_tip(__('Type at least two characters to search the user.'), false); + + $javascript_ajax_page = ui_get_full_url('ajax.php', false, false, false, false); + ?> + + '.html_print_image('images/setup.png', true, ['title' => __('Configure Integria IMS')]).''; + $list_tab['text'] = ''.html_print_image('images/list.png', true, ['title' => __('Ticket list')]).''; + $create_tab['text'] = ''.html_print_image('images/pencil.png', true, ['title' => __('New ticket')]).''; + + switch ($active_tab) { + case 'setup_tab': + $setup_tab['active'] = true; + $list_tab['active'] = false; + $create_tab['active'] = false; + break; + + case 'list_tab': + $setup_tab['active'] = false; + $list_tab['active'] = true; + $create_tab['active'] = false; + break; + + case 'create_tab': + $setup_tab['active'] = false; + $list_tab['active'] = false; + $create_tab['active'] = true; + break; + + default: + $setup_tab['active'] = false; + $list_tab['active'] = false; + $create_tab['active'] = false; + break; + } + + if ($view) { + $create_tab['text'] = ''.html_print_image('images/pencil.png', true, ['title' => __('Edit ticket')]).''; + $view_tab['text'] = ''.html_print_image('images/operation.png', true, ['title' => __('View ticket')]).''; + // When the current page is the View page. + if (!$active_tab) { + $view_tab['active'] = true; + } + } + + $onheader = []; + + if (check_acl($config['id_user'], 0, 'IR') && $view) { + $onheader['view'] = $view_tab; + } + + if (check_acl($config['id_user'], 0, 'PM')) { + $onheader['configure'] = $setup_tab; + } + + if (check_acl($config['id_user'], 0, 'IR')) { + $onheader['list'] = $list_tab; + } + + if (check_acl($config['id_user'], 0, 'IW')) { + $onheader['create'] = $create_tab; + } + + return $onheader; +} + + +/** + * Gets all the details of Integria IMS API + * + * @param string $details Type of API call. + * @param number $detail_index Send index if you want return the text. + * + * @return string or array with result of API call. + */ +function integriaims_get_details($details, $detail_index=false) +{ + global $config; + + switch ($details) { + case 'status': + $operation = 'get_incidents_status'; + break; + + case 'group': + $operation = 'get_groups'; + break; + + case 'priority': + $operation = 'get_incident_priorities'; + break; + + case 'resolution': + $operation = 'get_incidents_resolutions'; + break; + + case 'type': + $operation = 'get_types'; + break; + + default: + // code... + break; + } + + $api_call = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], $operation); + $result = []; + get_array_from_csv_data_pair($api_call, $result); + + if ($detail_index !== false) { + if ($result[$detail_index] == '' || $result[$detail_index] === null) { + return __('None'); + } else { + return $result[$detail_index]; + } + } else { + return $result; + } +} + + +/** + * Perform an API call to Integria IMS. + * + * @param string API host URL. + * @param string User name. + * @param string User password. + * @param string API password. + * @param string API Operation. + * @param array Array with parameters required by the API function. + * + * @return boolean True if API request succeeded, false if API request failed. + */ +function integria_api_call($api_hostname, $user, $user_pass, $api_pass, $operation, $params_array=[], $show_credentials_error_msg=false) +{ + $params_string = implode(',', $params_array); + + $url_data = [ + 'user' => $user, + 'user_pass' => $user_pass, + 'pass' => $api_pass, + 'op' => $operation, + 'params' => html_entity_decode($params_string), + ]; + + // Build URL for API request. + $url = $api_hostname.'/integria/include/api.php'; + + // ob_start(); + // $out = fopen('php://output', 'w'); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $url_data); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_VERBOSE, true); + curl_setopt($ch, CURLOPT_STDERR, $out); + $result = curl_exec($ch); + + // fclose($out); + // $debug = ob_get_clean(); + $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); + + $error = false; + + if ($result === false) { + $error = curl_error($ch); + } + + curl_close($ch); + + if ($error === true || $http_status !== 200) { + if ($show_credentials_error_msg === true) { + ui_print_error_message(__('API request failed. Please check Integria IMS\' access credentials in Pandora setup.')); + } + + return false; + } else { + return $result; + } +} + + +// Parse CSV consisting of one or more lines of the form key-value pair into an array. +function get_array_from_csv_data_pair($csv_data, &$array_values) +{ + $csv_array = explode("\n", $csv_data); + + foreach ($csv_array as $csv_value) { + if (empty($csv_value)) { + continue; + } + + $new_csv_value = str_getcsv($csv_value); + + $array_values[$new_csv_value[0]] = $new_csv_value[1]; + } +} + + +/** + * Parse CSV consisting of all lines into an array. + * + * @param string $csv_data Data returned of csv api call. + * @param string $array_values Returned array. + * @param array $index Array to create an associative index (opcional). + */ +function get_array_from_csv_data_all($csv_data, &$array_values, $index=false) +{ + $csv_array = explode("\n", $csv_data); + + foreach ($csv_array as $csv_value) { + if (empty($csv_value)) { + continue; + } + + $new_csv_value = str_getcsv($csv_value); + + if ($index !== false) { + foreach ($new_csv_value as $key => $value) { + $new_csv_value_index[$index[$key]] = str_replace(':::', ',', $value); + ; + } + + $array_values[$new_csv_value[0]] = $new_csv_value_index; + } else { + $new_csv_value_comma = array_map( + function ($item) { + return str_replace(':::', ',', $item); + }, + $new_csv_value + ); + $array_values[$new_csv_value[0]] = $new_csv_value_comma; + } + } +} + + +/** + * Print priority for Integria IMS with colors. + * + * @param string $priority value of priority in Integria IMS. + * @param string $priority_label text shown in color box. + * + * @return HTML code to print the color box. + */ +function ui_print_integria_incident_priority($priority, $priority_label) +{ + global $config; + + $output = ''; + switch ($priority) { + case 0: + $color = COL_UNKNOWN; + break; + + case 1: + $color = COL_NORMAL; + break; + + case 10: + $color = COL_NOTINIT; + break; + + case 2: + $color = COL_WARNING; + break; + + case 3: + $color = COL_ALERTFIRED; + break; + + case 4: + $color = COL_CRITICAL; + break; + } + + $output = '
'; + $output .= $priority_label; + $output .= '
'; + + return $output; +} + + +/** + * Get tickets from Integria IMS. + * + * @param array $tickets_filters Filters to send to API. + * + * @return array Tickets returned by API call. + */ +function get_tickets_integriaims($tickets_filters) +{ + global $config; + + // Filters. + $incident_text = $tickets_filters['incident_text']; + $incident_status = $tickets_filters['incident_status']; + $incident_group = $tickets_filters['incident_group']; + $incident_owner = $tickets_filters['incident_owner']; + $incident_creator = $tickets_filters['incident_creator']; + $incident_priority = $tickets_filters['incident_priority']; + $incident_resolution = $tickets_filters['incident_resolution']; + $created_from = $tickets_filters['created_from']; + $created_to = $tickets_filters['created_to']; + + // API call. + $result_api_call_list = integria_api_call( + $config['integria_hostname'], + $config['integria_user'], + $config['integria_pass'], + $config['integria_api_pass'], + 'get_incidents', + [ + $incident_text, + $incident_status, + $incident_group, + $incident_priority, + '0', + $incident_owner, + $incident_creator, + ] + ); + + // Return array of api call 'get_incidents'. + $array_get_incidents = []; + get_array_from_csv_data_all($result_api_call_list, $array_get_incidents); + + // Modify $array_get_incidents if filter for resolution exists. + $filter_resolution = []; + foreach ($array_get_incidents as $key => $value) { + if ($incident_resolution !== '' && ($array_get_incidents[$key][12] == $incident_resolution)) { + $filter_resolution[$key] = $array_get_incidents[$key]; + continue; + } + } + + if ($incident_resolution !== '') { + $array_get_incidents = $filter_resolution; + } + + // Modify $array_get_incidents if filter for date is selected. + if ($created_from !== '' && $created_to !== '') { + $date = []; + $date_utimestamp = []; + foreach ($array_get_incidents as $key => $value) { + // Change format date / to -. + $date[$key] = date('Y-m-d', strtotime($array_get_incidents[$key][9])); + // Covert date to utimestamp. + $date_utimestamp[$key] = strtotime($date[$key]); + } + + // Change format date / to -. + $created_from_date = date('Y-m-d', strtotime($created_from)); + $created_to_date = date('Y-m-d', strtotime($created_to)); + + // Covert date to utimestamp. + $created_from_timestamp = strtotime($created_from_date); + $created_to_timestamp = strtotime($created_to_date); + + // Dates within the selected period. + $selected_period = array_filter( + $date_utimestamp, + function ($value) use ($created_from_timestamp, $created_to_timestamp) { + return ($value >= $created_from_timestamp && $value <= $created_to_timestamp); + } + ); + + // Return incidents with the correct dates. + $filter_date = []; + foreach ($array_get_incidents as $key => $value) { + foreach ($selected_period as $index => $value) { + if ($array_get_incidents[$key][0] == $index) { + $filter_date[$key] = $array_get_incidents[$key]; + continue; + } + } + } + + $array_get_incidents = $filter_date; + } + + return $array_get_incidents; +} diff --git a/pandora_console/include/functions_io.php b/pandora_console/include/functions_io.php index 32c66ca1e3..baddb18531 100755 --- a/pandora_console/include/functions_io.php +++ b/pandora_console/include/functions_io.php @@ -507,7 +507,7 @@ function ___($string /*, variable arguments */) } -/* +/** * json_encode for multibyte characters. * * @param string Text string to be encoded. @@ -528,7 +528,7 @@ function io_json_mb_encode($string, $encode_options=0) } -/* +/** * Prepare the given password to be stored in the Pandora FMS Database, * encrypting it if necessary. * @@ -541,16 +541,22 @@ function io_input_password($password) global $config; enterprise_include_once('include/functions_crypto.php'); - $ciphertext = enterprise_hook('openssl_encrypt_decrypt', ['encrypt', io_safe_output($password)]); + $ciphertext = enterprise_hook( + 'openssl_encrypt_decrypt', + [ + 'encrypt', + io_safe_input($password), + ] + ); if ($ciphertext === ENTERPRISE_NOT_HOOK) { - return $password; + return io_safe_input($password); } return $ciphertext; } -/* +/** * Process the given password read from the Pandora FMS Database, * decrypting it if necessary. * @@ -563,10 +569,17 @@ function io_output_password($password) global $config; enterprise_include_once('include/functions_crypto.php'); - $plaintext = enterprise_hook('openssl_encrypt_decrypt', ['decrypt', io_safe_output($password)]); + $plaintext = enterprise_hook( + 'openssl_encrypt_decrypt', + [ + 'decrypt', + $password, + ] + ); + if ($plaintext === ENTERPRISE_NOT_HOOK) { - return $password; + return io_safe_output($password); } - return $plaintext; + return io_safe_output($plaintext); } diff --git a/pandora_console/include/functions_menu.php b/pandora_console/include/functions_menu.php index 98191d231f..36785064ef 100644 --- a/pandora_console/include/functions_menu.php +++ b/pandora_console/include/functions_menu.php @@ -545,7 +545,6 @@ function menu_add_extras(&$menu) $menu_extra['estado']['sub']['godmode/snmpconsole/snmp_filters']['text'] = __('SNMP filters'); $menu_extra['estado']['sub']['enterprise/godmode/snmpconsole/snmp_trap_editor']['text'] = __('SNMP trap editor'); $menu_extra['estado']['sub']['snmpconsole']['sub2']['godmode/snmpconsole/snmp_trap_generator']['text'] = __('SNMP trap generator'); - $menu_extra['estado']['sub']['snmpconsole']['sub2']['operation/snmpconsole/snmp_view']['text'] = __('SNMP console'); $menu_extra['workspace']['sub']['operation/incidents/incident_detail']['text'] = __('Manage incident'); diff --git a/pandora_console/include/functions_modules.php b/pandora_console/include/functions_modules.php index fbee2a5331..39cc5b4a49 100755 --- a/pandora_console/include/functions_modules.php +++ b/pandora_console/include/functions_modules.php @@ -2654,21 +2654,18 @@ function modules_get_relations($params=[]) } $modules_type = ''; + $modules_type_filter = ''; if (isset($params['modules_type'])) { - $modules_type = $params['modules_type']; + $module_type = 'INNER JOIN ttipo_modulo ttm ON tam.id_tipo_modulo = ttm.id_tipo'; + $modules_type_filter = sprintf( + "AND ttm.nombre = '%s'", + $params['modules_type'] + ); } - $sql = 'SELECT DISTINCT tmr.id, tmr.module_a, tmr.module_b, - tmr.disable_update, tmr.type - FROM tmodule_relationship tmr, - tagente_modulo tam, - tagente ta, - ttipo_modulo ttm - WHERE '; - - $agent_filter = ''; - if ($id_agent > 0) { - $agent_filter = sprintf('AND ta.id_agente = %d', $id_agent); + $distinct = ''; + if (empty($params)) { + $distinct = 'DISTINCT'; } $module_a_filter = ''; @@ -2678,6 +2675,11 @@ function modules_get_relations($params=[]) $module_b_filter = sprintf('AND tmr.module_b = %d', $id_module); } + $agent_filter = ''; + if ($id_agent > 0) { + $agent_filter = sprintf('AND ta.id_agente = %d', $id_agent); + } + $disabled_update_filter = ''; if ($disabled_update >= 0) { $disabled_update_filter = sprintf( @@ -2686,22 +2688,25 @@ function modules_get_relations($params=[]) ); } - $modules_type_filter = ''; - if ($modules_type != '') { - $modules_type_filter = sprintf( - "AND (tam.id_tipo_modulo = ttm.id_tipo AND ttm.nombre = '%s')", - $modules_type - ); - } - - $sql .= "( (tmr.module_a = tam.id_agente_modulo - $module_a_filter) - OR (tmr.module_b = tam.id_agente_modulo - $module_b_filter) ) - AND tam.id_agente = ta.id_agente - $agent_filter - $disabled_update_filter - $modules_type_filter"; + $sql = sprintf( + 'SELECT %s tmr.id, tmr.module_a, tmr.module_b, + tmr.disable_update, tmr.type + FROM tmodule_relationship tmr + INNER JOIN tagente_modulo tam + ON (tmr.module_a = tam.id_agente_modulo %s) + OR (tmr.module_b = tam.id_agente_modulo %s) + INNER JOIN tagente ta + ON tam.id_agente = ta.id_agente + %s + WHERE 1=1 %s %s %s', + $distinct, + $module_a_filter, + $module_b_filter, + $module_type, + $agent_filter, + $disabled_update_filter, + $modules_type_filter + ); return db_get_all_rows_sql($sql); } diff --git a/pandora_console/include/functions_networkmap.php b/pandora_console/include/functions_networkmap.php index e4fb19e814..dda25538ee 100644 --- a/pandora_console/include/functions_networkmap.php +++ b/pandora_console/include/functions_networkmap.php @@ -2327,7 +2327,13 @@ function migrate_older_open_maps($id) $new_map_filter = []; $new_map_filter['dont_show_subgroups'] = $old_networkmap['dont_show_subgroups']; $new_map_filter['node_radius'] = 40; - $new_map_filter['id_migrate_map'] = $id; + $new_map_filter['x_offs'] = 0; + $new_map_filter['y_offs'] = 0; + $new_map_filter['z_dash'] = '0.5'; + $new_map_filter['node_sep'] = '0.1'; + $new_map_filter['rank_sep'] = 1; + $new_map_filter['mindist'] = 1; + $new_map_filter['kval'] = '0.1'; $map_values['filter'] = json_encode($new_map_filter); $map_values['description'] = 'Mapa open migrado'; @@ -2340,11 +2346,7 @@ function migrate_older_open_maps($id) $map_values['source_period'] = 60; $map_values['source'] = 0; $map_values['source_data'] = $old_networkmap['id_group']; - if ($old_networkmap['type'] == 'radial_dinamic') { - $map_values['generation_method'] = 6; - } else { - $map_values['generation_method'] = 4; - } + $map_values['generation_method'] = 3; $map_values['generated'] = 0; diff --git a/pandora_console/include/functions_planned_downtimes.php b/pandora_console/include/functions_planned_downtimes.php index 7f1a587b65..a9b701241b 100644 --- a/pandora_console/include/functions_planned_downtimes.php +++ b/pandora_console/include/functions_planned_downtimes.php @@ -748,7 +748,9 @@ function planned_downtimes_created($values) 'return' => false, 'message' => __('Not created. Error inserting data').'. '.__('The end date must be higher than the current time'), ]; - } else if ($values['type_execution'] == 'once' && $values['date_from'] >= $values['date_to']) { + } else if ($values['type_execution'] == 'once' && ($values['date_from'] > $values['date_to']) + || (($values['date_from'] == $values['date_to']) && ($values['periodically_time_from'] >= $values['periodically_time_to'])) + ) { return [ 'return' => false, 'message' => __('Not created. Error inserting data').'. '.__('The end date must be higher than the start date'), @@ -794,6 +796,11 @@ function planned_downtimes_created($values) 'return' => false, 'message' => __('Not created. Error inserting data').'. '.__('There is no group with such id'), ]; + } else if (!$values['date_from'] || !$values['date_to']) { + return [ + 'return' => false, + 'message' => __('Not created. Error inserting data').'. '.__('Date is wrong formatted'), + ]; } else { if (trim(io_safe_output($values['name'])) != '') { if (!$check) { diff --git a/pandora_console/include/functions_reporting.php b/pandora_console/include/functions_reporting.php index 3494eed389..a5ae07df3e 100755 --- a/pandora_console/include/functions_reporting.php +++ b/pandora_console/include/functions_reporting.php @@ -282,6 +282,15 @@ function reporting_make_reporting_data( $agents_to_macro = $content['id_agent']; } + // Metaconsole connection. + if (is_metaconsole()) { + $server = metaconsole_get_connection_names(); + $connection = metaconsole_get_connection($server); + if (metaconsole_connect($connection) != NOERR) { + continue; + } + } + if (isset($content['style']['name_label'])) { // Add macros name. $items_label = []; @@ -294,14 +303,6 @@ function reporting_make_reporting_data( $metaconsole_on = is_metaconsole(); $server_name = $content['server_name']; - // Metaconsole connection. - if ($metaconsole_on && $server_name != '') { - $connection = metaconsole_get_connection($server_name); - if (!metaconsole_load_external_db($connection)) { - continue; - } - } - $items_label['agent_description'] = agents_get_description( $content['id_agent'] ); @@ -505,42 +506,6 @@ function reporting_make_reporting_data( ); break; - case 'MTTR': - $report['contents'][] = reporting_value( - $report, - $content, - 'MTTR', - $pdf - ); - break; - - case 'MTBF': - $report['contents'][] = reporting_value( - $report, - $content, - 'MTBF', - $pdf - ); - break; - - case 'TTO': - $report['contents'][] = reporting_value( - $report, - $content, - 'TTO', - $pdf - ); - break; - - case 'TTRT': - $report['contents'][] = reporting_value( - $report, - $content, - 'TTRT', - $pdf - ); - break; - case 'agent_configuration': $report['contents'][] = io_safe_output( reporting_agent_configuration( @@ -2823,13 +2788,12 @@ function reporting_group_report($report, $content) $content['name'] = __('Group Report'); } - if ($config['metaconsole']) { - $id_meta = metaconsole_get_id_server($content['server_name']); - - $server = metaconsole_get_connection_by_id($id_meta); - metaconsole_connect($server); + if (is_metaconsole()) { + $server = metaconsole_get_connection_names(); + $connection = metaconsole_get_connection($server); } + $return['server_name'] = $server[0]; $return['title'] = $content['name']; $return['subtitle'] = groups_get_name($content['id_group'], true); $return['description'] = $content['description']; @@ -3105,6 +3069,13 @@ function reporting_historical_data($report, $content) $content['name'] = __('Historical data'); } + if (is_metaconsole()) { + $id_meta = metaconsole_get_id_server($content['server_name']); + + $server = metaconsole_get_connection_by_id($id_meta); + $connection = metaconsole_connect($server); + } + $id_agent = agents_get_module_id( $content['id_agent_module'] ); @@ -3196,6 +3167,10 @@ function reporting_historical_data($report, $content) $return['data'] = $data; + if (is_metaconsole() && $connection > 0) { + metaconsole_restore_db(); + } + return reporting_check_structure_content($return); } @@ -3264,6 +3239,7 @@ function reporting_database_serialized($report, $content) } $return['keys'] = $keys; + $return['agent_name_db'] = agents_get_name($id_agent); $return['agent_name'] = $agent_alias; $return['module_name'] = $module_name; @@ -3476,7 +3452,7 @@ function reporting_network_interfaces_report($report, $content, $type='dinamic', $return['failed'] = null; $return['data'] = []; - if ($config['metaconsole']) { + if (is_metaconsole()) { $server_names = metaconsole_get_connection_names(); if (isset($server_names) && is_array($server_names)) { foreach ($server_names as $key => $value) { @@ -3493,7 +3469,8 @@ function reporting_network_interfaces_report($report, $content, $type='dinamic', $content, $report, $fullscale, - $pdf + $pdf, + $id_meta ); metaconsole_restore_db(); } @@ -4178,6 +4155,19 @@ function reporting_sql_graph( $return['description'] = $content['description']; $return['date'] = reporting_get_date_text(); + $module_source = db_get_all_rows_sql( + 'SELECT id_agent_module + FROM tgraph_source + WHERE id_graph = '.$content['id_gs'] + ); + + if (isset($module_source) && is_array($module_source)) { + $modules = []; + foreach ($module_source as $key => $value) { + $modules[$key] = $value['id_agent_module']; + } + } + switch ($type) { case 'dinamic': case 'static': @@ -4194,6 +4184,16 @@ function reporting_sql_graph( break; case 'data': + $data = []; + foreach ($modules as $key => $value) { + $data[$value] = modules_get_agentmodule_data( + $value, + $content['period'], + $report['datetime'] + ); + } + + $return['chart'] = $data; break; } @@ -4267,6 +4267,7 @@ function reporting_monitor_report($report, $content) ); } + $return['agent_name_db'] = agents_get_name($id_agent); $return['agent_name'] = $agent_alias; $return['module_name'] = $module_name; @@ -4394,6 +4395,7 @@ function reporting_netflow( switch ($type) { case 'dinamic': case 'static': + case 'data': $return['chart'] = netflow_draw_item( ($report['datetime'] - $content['period']), $report['datetime'], @@ -4438,6 +4440,7 @@ function reporting_prediction_date($report, $content) $agent_name = io_safe_output( modules_get_agentmodule_agent_alias($content['id_agent_module']) ); + $agent_name_db = io_safe_output(modules_get_agentmodule_agent_name($content['id_agent_module'])); $return['title'] = $content['name']; $return['subtitle'] = $agent_name.' - '.$module_name; @@ -4445,6 +4448,7 @@ function reporting_prediction_date($report, $content) $return['date'] = reporting_get_date_text($report, $content); $return['label'] = (isset($content['style']['label'])) ? $content['style']['label'] : ''; + $return['agent_name_db'] = $agent_name_db; $return['agent_name'] = $agent_name; $return['module_name'] = $module_name; @@ -4489,12 +4493,14 @@ function reporting_projection_graph( $module_name = io_safe_output(modules_get_agentmodule_name($content['id_agent_module'])); $agent_name = io_safe_output(modules_get_agentmodule_agent_alias($content['id_agent_module'])); + $agent_name_db = io_safe_output(modules_get_agentmodule_agent_name($content['id_agent_module'])); $return['title'] = $content['name']; $return['subtitle'] = $agent_name.' - '.$module_name; $return['description'] = $content['description']; $return['date'] = reporting_get_date_text($report, $content); $return['label'] = (isset($content['style']['label'])) ? $content['style']['label'] : ''; + $return['agent_name_db'] = $agent_name_db; $return['agent_name'] = $agent_name; $return['module_name'] = $module_name; @@ -4690,22 +4696,6 @@ function reporting_value($report, $content, $type, $pdf=false) case 'sum': $return['type'] = 'sumatory'; break; - - case 'MTTR': - $return['type'] = 'MTTR'; - break; - - case 'MTBF': - $return['type'] = 'MTBF'; - break; - - case 'TTO': - $return['type'] = 'TTO'; - break; - - case 'TTRT': - $return['type'] = 'TTRT'; - break; } if (empty($content['name'])) { @@ -4725,22 +4715,6 @@ function reporting_value($report, $content, $type, $pdf=false) case 'sum': $content['name'] = __('Summatory'); break; - - case 'MTTR': - $content['name'] = __('MTTR'); - break; - - case 'MTBF': - $content['name'] = __('MTBF'); - break; - - case 'TTO': - $content['name'] = __('TTO'); - break; - - case 'TTRT': - $content['name'] = __('TTRT'); - break; } } @@ -4757,6 +4731,9 @@ function reporting_value($report, $content, $type, $pdf=false) $agent_name = io_safe_output( modules_get_agentmodule_agent_alias($content['id_agent_module']) ); + $agent_name_db = io_safe_output( + modules_get_agentmodule_agent_name($content['id_agent_module']) + ); $unit = db_get_value( 'unit', 'tagente_modulo', @@ -4773,6 +4750,7 @@ function reporting_value($report, $content, $type, $pdf=false) $return['id_agent'] = $content['id_agent']; $return['id_agent_module'] = $content['id_agent_module']; + $return['agent_name_db'] = $agent_name_db; $return['agent_name'] = $agent_name; $return['module_name'] = $module_name; @@ -4865,22 +4843,23 @@ function reporting_value($report, $content, $type, $pdf=false) if ($content['visual_format'] != 2) { $time_begin = db_get_row_sql('select utimestamp from tagente_datos where id_agente_modulo ='.$content['id_agent_module'], true); - for ($i = $report['datetime']; $i > ($report['datetime'] - $content['period']); $i -= $content['lapse']) { + + for ($i = ($report['datetime'] - $content['period']); $i < $report['datetime']; $i += $content['lapse']) { $row = []; - $row[__('Lapse')] = date('Y-m-d H:i:s', ($i - $content['lapse'] + 1)).' to '.date('Y-m-d H:i:s', $i); + $row[__('Lapse')] = date('Y-m-d H:i:s', ($i + 1)).' to '.date('Y-m-d H:i:s', (($i + $content['lapse']) )); if ($i > $time_begin['utimestamp']) { switch ($type) { case 'max': - $row[__('Maximun')] = format_for_graph(reporting_get_agentmodule_data_max($content['id_agent_module'], $content['lapse'], $i), $config['graph_precision']).' '.$unit; + $row[__('Maximun')] = format_for_graph(reporting_get_agentmodule_data_max($content['id_agent_module'], $content['lapse'], ($i + $content['lapse'])), $config['graph_precision']).' '.$unit; break; case 'min': - $row[__('Maximun')] = format_for_graph(reporting_get_agentmodule_data_min($content['id_agent_module'], $content['lapse'], $i), $config['graph_precision']).' '.$unit; + $row[__('Maximun')] = format_for_graph(reporting_get_agentmodule_data_min($content['id_agent_module'], $content['lapse'], ($i + $content['lapse'])), $config['graph_precision']).' '.$unit; break; case 'avg': - $row[__('Maximun')] = format_for_graph(reporting_get_agentmodule_data_average($content['id_agent_module'], $content['lapse'], $i), $config['graph_precision']).' '.$unit; + $row[__('Maximun')] = format_for_graph(reporting_get_agentmodule_data_average($content['id_agent_module'], $content['lapse'], ($i + $content['lapse'])), $config['graph_precision']).' '.$unit; break; } } else { @@ -4903,7 +4882,8 @@ function reporting_value($report, $content, $type, $pdf=false) $value = reporting_get_agentmodule_data_sum( $content['id_agent_module'], $content['period'], - $report['datetime'] + $report['datetime'], + $content['uncompressed_module'] ); if (!$config['simple_module_value']) { $formated_value = $value; @@ -4911,50 +4891,6 @@ function reporting_value($report, $content, $type, $pdf=false) $formated_value = format_for_graph($value, $config['graph_precision']).' '.$unit; } break; - - case 'MTTR': - $value = reporting_get_agentmodule_mttr( - $content['id_agent_module'], - $content['period'], - $report['datetime'] - ); - $formated_value = null; - break; - - case 'MTBF': - $value = reporting_get_agentmodule_mtbf( - $content['id_agent_module'], - $content['period'], - $report['datetime'] - ); - $formated_value = null; - break; - - case 'TTO': - $value = reporting_get_agentmodule_tto( - $content['id_agent_module'], - $content['period'], - $report['datetime'] - ); - if ($value == 0) { - $formated_value = null; - } else { - $formated_value = human_time_description_raw($value); - } - break; - - case 'TTRT': - $value = reporting_get_agentmodule_ttr( - $content['id_agent_module'], - $content['period'], - $report['datetime'] - ); - if ($value == 0) { - $formated_value = null; - } else { - $formated_value = human_time_description_raw($value); - } - break; } $return['data'] = [ @@ -7487,10 +7423,12 @@ function reporting_custom_graph( if ($type_report == 'custom_graph') { if (is_metaconsole()) { - $id_meta = metaconsole_get_id_server($content['server_name']); - $server = metaconsole_get_connection_by_id($id_meta); - if (metaconsole_connect($server) != NOERR) { - return false; + $servers = metaconsole_get_connection_names(); + foreach ($servers as $server) { + $connection = metaconsole_get_connection($server); + if (metaconsole_connect($connection) != NOERR) { + continue; + } } } } @@ -7542,8 +7480,35 @@ function reporting_custom_graph( $content['name'] = __('Simple graph'); } + $module_source = db_get_all_rows_sql( + 'SELECT id_agent_module + FROM tgraph_source + WHERE id_graph = '.$content['id_gs'] + ); + + if (isset($module_source) && is_array($module_source)) { + $modules = []; + foreach ($module_source as $key => $value) { + $modules[$key] = $value['id_agent_module']; + } + } + + $agent_description = agents_get_description($id_agent); + $agent_group = agents_get_agent_group($id_agent); + $agent_address = agents_get_address($id_agent); + $agent_alias = agents_get_alias($id_agent); + $module_name = modules_get_agentmodule_name( + $id_agent_module + ); + + $module_description = modules_get_agentmodule_descripcion( + $id_agent_module + ); + $return['title'] = $content['name']; $return['subtitle'] = io_safe_output($graph['name']); + $return['agent_name'] = $agent_alias; + $return['module_name'] = $module_name; $return['description'] = $content['description']; $return['date'] = reporting_get_date_text( $report, @@ -7587,6 +7552,19 @@ function reporting_custom_graph( ); break; + + case 'data': + $data = []; + foreach ($modules as $key => $value) { + $data[$value] = modules_get_agentmodule_data( + $value, + $content['period'], + $report['datetime'] + ); + } + + $return['chart'] = $data; + break; } if ($type_report == 'custom_graph') { @@ -7671,6 +7649,7 @@ function reporting_simple_graph( $return['title'] = $content['name']; $return['subtitle'] = $agent_alias.' - '.$module_name; + $return['agent_name_db'] = agents_get_name($id_agent); $return['agent_name'] = $agent_alias; $return['module_name'] = $module_name; $return['description'] = $content['description']; @@ -10725,17 +10704,19 @@ function reporting_get_agentmodule_data_min($id_agent_module, $period=0, $date=0 * @param int Agent module id to get the sumatory. * @param int Period of time to check (in seconds) * @param int Top date to check the values. Default current time. + * @param boolean Show uncompressed data from module * * @return float The sumatory of the module values in the interval. */ function reporting_get_agentmodule_data_sum( $id_agent_module, $period=0, - $date=0 + $date=0, + $uncompressed_module=true ) { global $config; - // Initialize variables + // Initialize variables. if (empty($date)) { $date = get_system_time(); } @@ -10757,21 +10738,24 @@ function reporting_get_agentmodule_data_sum( $id_module_type ); $module_interval = modules_get_interval($id_agent_module); - $uncompressed_module = is_module_uncompressed($module_name); + // Check if module must be compressed. + if (!$uncompressed_module) { + $uncompressed_module = is_module_uncompressed($module_name); + } // Wrong module type if (is_module_data_string($module_name)) { return 0; } - // Incremental modules are treated differently + // Incremental modules are treated differently. $module_inc = is_module_inc($module_name); - if ($uncompressed_module) { - // Get module data + if (!$uncompressed_module) { + // Get module data. $interval_data = db_get_all_rows_sql( ' - SELECT * FROM tagente_datos + SELECT * FROM tagente_datos WHERE id_agente_modulo = '.(int) $id_agent_module.' AND utimestamp > '.(int) $datelimit.' AND utimestamp < '.(int) $date.' @@ -10792,7 +10776,7 @@ function reporting_get_agentmodule_data_sum( return false; } - // Set initial conditions + // Set initial conditions. $total = 0; $partial_total = 0; $count_sum = 0; @@ -10801,18 +10785,9 @@ function reporting_get_agentmodule_data_sum( $partial_total = 0; $count_sum = 0; - switch ($config['dbtype']) { - case 'mysql': - case 'postgresql': - // Do none - break; - - case 'oracle': - $data['datos'] = oracle_format_float_to_php($data['datos']); - break; - } - - if (!$module_inc) { + if (!$uncompressed_module) { + $total += $data['datos']; + } else if (!$module_inc) { foreach ($data['data'] as $val) { if (is_numeric($val['datos'])) { $partial_total += $val['datos']; @@ -10824,7 +10799,7 @@ function reporting_get_agentmodule_data_sum( continue; } - $total += ($partial_total / $count_sum); + $total += $partial_total; } else { $last = end($data['data']); $total += $last['datos']; diff --git a/pandora_console/include/functions_reporting_html.php b/pandora_console/include/functions_reporting_html.php index c2ace5699e..5dc38d3b9d 100644 --- a/pandora_console/include/functions_reporting_html.php +++ b/pandora_console/include/functions_reporting_html.php @@ -251,6 +251,7 @@ function reporting_html_print_report($report, $mini=false, $report_info=1) reporting_html_sql($table, $item); break; + case 'simple_baseline_graph': case 'simple_graph': reporting_html_graph($table, $item); break; @@ -287,22 +288,6 @@ function reporting_html_print_report($report, $mini=false, $report_info=1) reporting_html_sum_value($table, $item, $mini); break; - case 'MTTR': - reporting_html_MTTR_value($table, $item, $mini, true, true); - break; - - case 'MTBF': - reporting_html_MTBF_value($table, $item, $mini, true, true); - break; - - case 'TTO': - reporting_html_TTO_value($table, $item, $mini, false, true); - break; - - case 'TTRT': - reporting_html_TTRT_value($table, $item, $mini, false, true); - break; - case 'agent_configuration': reporting_html_agent_configuration($table, $item); break; @@ -315,10 +300,6 @@ function reporting_html_print_report($report, $mini=false, $report_info=1) reporting_html_prediction_date($table, $item, $mini); break; - case 'simple_baseline_graph': - reporting_html_graph($table, $item); - break; - case 'netflow_area': case 'netflow_data': case 'netflow_summary': @@ -2207,12 +2188,15 @@ function reporting_html_database_serialized($table, $item, $pdf=0) { $table1 = new stdClass(); $table1->width = '100%'; - $table1->head = [__('Date')]; + $table1->head = [ + __('Date'), + __('Data'), + ]; if (!empty($item['keys'])) { $table1->head = array_merge($table1->head, $item['keys']); } - $table1->style[0] = 'text-align: left'; + $table1->style[0] = 'text-align: center'; $table1->data = []; foreach ($item['data'] as $data) { @@ -2532,7 +2516,7 @@ function reporting_html_monitor_report($table, $item, $mini, $pdf=0) true ).' '.__('OK').': '.remove_right_zeros( number_format( - $item['data']['ok']['formated_value'], + $item['data']['ok']['value'], $config['graph_precision'] ) ).' %

'; @@ -2543,7 +2527,7 @@ function reporting_html_monitor_report($table, $item, $mini, $pdf=0) true ).' '.__('Not OK').': '.remove_right_zeros( number_format( - $item['data']['fail']['formated_value'], + $item['data']['fail']['value'], $config['graph_precision'] ) ).' % '.'

'; @@ -2728,30 +2712,6 @@ function reporting_html_agent_configuration( } -function reporting_html_TTRT_value(&$table, $item, $mini, $only_value=false, $check_empty=false) -{ - reporting_html_value($table, $item, $mini, $only_value, $check_empty); -} - - -function reporting_html_TTO_value(&$table, $item, $mini, $only_value=false, $check_empty=false) -{ - reporting_html_value($table, $item, $mini, $only_value, $check_empty); -} - - -function reporting_html_MTBF_value(&$table, $item, $mini, $only_value=false, $check_empty=false) -{ - reporting_html_value($table, $item, $mini, $only_value, $check_empty); -} - - -function reporting_html_MTTR_value(&$table, $item, $mini, $only_value=false, $check_empty=false) -{ - reporting_html_value($table, $item, $mini, $only_value, $check_empty); -} - - function reporting_html_sum_value(&$table, $item, $mini) { reporting_html_value($table, $item, $mini); diff --git a/pandora_console/include/functions_reports.php b/pandora_console/include/functions_reports.php index 0bf1f8fe70..e20fdd01fa 100755 --- a/pandora_console/include/functions_reports.php +++ b/pandora_console/include/functions_reports.php @@ -679,23 +679,6 @@ function reports_get_report_types($template=false, $not_editor=false) 'name' => __('Module Histogram graph'), ]; - $types['TTRT'] = [ - 'optgroup' => __('ITIL'), - 'name' => __('TTRT'), - ]; - $types['TTO'] = [ - 'optgroup' => __('ITIL'), - 'name' => __('TTO'), - ]; - $types['MTBF'] = [ - 'optgroup' => __('ITIL'), - 'name' => __('MTBF'), - ]; - $types['MTTR'] = [ - 'optgroup' => __('ITIL'), - 'name' => __('MTTR'), - ]; - $types['SLA'] = [ 'optgroup' => __('SLA'), 'name' => __('S.L.A.'), @@ -768,22 +751,34 @@ function reports_get_report_types($template=false, $not_editor=false) 'optgroup' => __('Grouped'), 'name' => __('General'), ]; - $types['group_report'] = [ - 'optgroup' => __('Grouped'), - 'name' => __('Group report'), - ]; + if (is_metaconsole()) { + if ($template === false) { + $types['group_report'] = [ + 'optgroup' => __('Grouped'), + 'name' => __('Group report'), + ]; + } + } else { + $types['group_report'] = [ + 'optgroup' => __('Grouped'), + 'name' => __('Group report'), + ]; + } + $types['exception'] = [ 'optgroup' => __('Grouped'), 'name' => __('Exception'), ]; if ($config['metaconsole'] != 1) { - $types['agent_module'] = [ - 'optgroup' => __('Grouped'), - 'name' => __('Agents/Modules'), - ]; + if (!$template) { + $types['agent_module'] = [ + 'optgroup' => __('Grouped'), + 'name' => __('Agents/Modules'), + ]; + } } - // Only pandora managers have access to the whole database + // Only pandora managers have access to the whole database. if (check_acl($config['id_user'], 0, 'PM')) { $types['sql'] = [ 'optgroup' => __('Grouped'), @@ -877,7 +872,7 @@ function reports_get_report_types($template=false, $not_editor=false) ]; } - if ($config['enterprise_installed']) { + if ($config['enterprise_installed'] && $template === false) { $types['event_report_log'] = [ 'optgroup' => __('Log'), 'name' => __('Log report'), diff --git a/pandora_console/include/functions_ui.php b/pandora_console/include/functions_ui.php index 4f529dbd43..ebc4091f97 100755 --- a/pandora_console/include/functions_ui.php +++ b/pandora_console/include/functions_ui.php @@ -39,7 +39,7 @@ if (isset($config['homedir'])) { /** - * Transform bbcode to HTML. + * Transform bbcode to HTML and truncate log. * * @param string $text Text. * @param array $allowed_tags Allowed_tags. @@ -48,16 +48,22 @@ if (isset($config['homedir'])) { */ function ui_bbcode_to_html($text, $allowed_tags=['[url]']) { - if (array_search('[url]', $allowed_tags) !== false) { - // If link hasn't http, add it. - if (preg_match('/https?:\/\//', $text)) { - $html_bbcode = '$2'; - } else { - $html_bbcode = '$2'; - } - + if (array_search('[url]', $allowed_tags) !== false || a) { // Replace bbcode format [url=www.example.org] String [/url] with or without http and slashes - $return = preg_replace('/\[url(?|](((?:https?:\/\/)?[^[]+))|(?:=[\'"]?((?:https?:\/\/)?[^]]+?)[\'"]?)](.+?))\[\/url]/', $html_bbcode, $text); + preg_match('/\[url(?|](((?:https?:\/\/)?[^[]+))|(?:=[\'"]?((?:https?:\/\/)?[^]]+?)[\'"]?)](.+?))\[\/url]/', $text, $matches); + if ($matches) { + $url = $matches[1]; + // Truncate text + $t_text = ui_print_truncate_text($matches[2]); + // If link hasn't http, add it. + if (preg_match('/https?:\/\//', $text)) { + $return = ''.$t_text.''; + } else { + $return = ''.$t_text.''; + } + } else { + $return = ui_print_truncate_text($text); + } } return $return; @@ -162,6 +168,10 @@ function ui_print_truncate_text($text, $numChars=GENERIC_SIZE_TEXT, $showTextInA } if ($showTextInAToopTip) { + if (is_string($showTextInAToopTip)) { + $text = ui_print_truncate_text($showTextInAToopTip, ($numChars * 2), false, true, false); + } + $truncateText = $truncateText.ui_print_help_tip(htmlspecialchars($text), true); } else { if ($style !== false) { @@ -2517,9 +2527,22 @@ function ui_print_module_warn_value( $str_warning, $max_critical, $min_critical, - $str_critical + $str_critical, + $warning_inverse=0, + $critical_inverse=0 ) { - $data = ""; + $war_inv = ''; + $crit_inv = ''; + + if ($warning_inverse == 1) { + $war_inv = ' (inv)'; + } + + if ($critical_inverse == 1) { + $crit_inv = ' (inv)'; + } + + $data = ""; if ($max_warning != $min_warning) { $data .= format_for_graph($max_warning).'/'.format_for_graph($min_warning); @@ -2679,6 +2702,7 @@ function get_shape_status_set($type) case STATUS_MODULE_UNKNOWN: case STATUS_AGENT_UNKNOWN: case STATUS_AGENT_DOWN: + case STATUS_AGENT_NO_MONITORS: $return = ['class' => 'status_rounded_rectangles']; break; @@ -3186,14 +3210,18 @@ function ui_print_datatable(array $parameters) $.fn.dataTable.ext.errMode = "none"; $.fn.dataTable.ext.classes.sPageButton = "'.$pagination_class.'"; dt_'.$table_id.' = $("#'.$table_id.'").DataTable({ - '; + drawCallback: function(settings) {'; if (isset($parameters['drawCallback'])) { - $js .= 'drawCallback: function(settings) { - '.$parameters['drawCallback'].' - },'; + $js .= $parameters['drawCallback']; } $js .= ' + if (dt_'.$table_id.'.page.info().pages > 1) { + $("#'.$table_id.'_wrapper > .dataTables_paginate.paging_simple_numbers").show() + } else { + $("#'.$table_id.'_wrapper > .dataTables_paginate.paging_simple_numbers").hide() + } + }, processing: true, serverSide: true, paging: true, @@ -3299,6 +3327,7 @@ function ui_print_datatable(array $parameters) dt_'.$table_id.'.draw().page(0) }); }); + '; // Order. @@ -5646,3 +5675,62 @@ function ui_print_breadcrums($tab_name) return $section; } + + +/** + * Show last comment + * + * @param array $comments array with comments + * + * @return string HTML string with the last comment of the events. + */ +function ui_print_comments($comments) +{ + global $config; + + $comments = explode('
', $comments); + $comments = str_replace(["\n", ' '], '
', $comments); + if (is_array($comments)) { + foreach ($comments as $comm) { + if (empty($comm)) { + continue; + } + + $comments_array[] = json_decode(io_safe_output($comm), true); + } + } + + foreach ($comments_array as $comm) { + // Show the comments more recent first. + if (is_array($comm)) { + $last_comment[] = array_reverse($comm); + } + } + + // Only show the last comment. If commment its too long,the comment will short with ... + // If $config['prominent_time'] is timestamp the date show Month, day, hour and minutes. + // Else show comments hours ago + if ($last_comment[0][0]['action'] != 'Added comment') { + $last_comment[0][0]['comment'] = $last_comment[0][0]['action']; + } + + $short_comment = substr($last_comment[0][0]['comment'], 0, '80px'); + if ($config['prominent_time'] == 'timestamp') { + $comentario = ''.date($config['date_format'], $last_comment[0][0]['utimestamp']).' ('.$last_comment[0][0]['id_user'].'): '.$last_comment[0][0]['comment'].''; + + if (strlen($comentario) > '200px') { + $comentario = ''.date($config['date_format'], $last_comment[0][0]['utimestamp']).' ('.$last_comment[0][0]['id_user'].'): '.$short_comment.'...'; + } + } else { + $rest_time = (time() - $last_comment[0][0]['utimestamp']); + $time_last = (($rest_time / 60) / 60); + $comentario = ''.number_format($time_last, 0).'  Hours  ('.$last_comment[0][0]['id_user'].'): '.$last_comment[0][0]['comment'].''; + + if (strlen($comentario) > '200px') { + $comentario = ''.number_format($time_last, 0).'  Hours  ('.$last_comment[0][0]['id_user'].'): '.$short_comment.'...'; + } + } + + return io_safe_output($comentario); + +} diff --git a/pandora_console/include/gettext.php b/pandora_console/include/gettext.php index 152040f327..5d3abd83fe 100644 --- a/pandora_console/include/gettext.php +++ b/pandora_console/include/gettext.php @@ -104,7 +104,7 @@ class gettext_reader { * @param boolean enable_cache Enable or disable caching of strings (default on) */ function gettext_reader($Reader, $enable_cache = true) { - $machine = @shell_exec('uname -m'); + $machine = php_uname("m"); $enabled64Bits = false; if (preg_match('/64/', $machine)) { diff --git a/pandora_console/include/graphs/fgraph.php b/pandora_console/include/graphs/fgraph.php index d8012c15dd..40c79bbf51 100644 --- a/pandora_console/include/graphs/fgraph.php +++ b/pandora_console/include/graphs/fgraph.php @@ -170,17 +170,7 @@ function vbar_graph( setup_watermark($water_mark, $water_mark_file, $water_mark_url); if (empty($chart_data)) { - return html_print_image( - $no_data_image, - true, - [ - 'width' => $width, - 'height' => $height, - 'title' => __('No data to show'), - ], - false, - true - ); + return graph_nodata_image($width, $height, 'vbar'); } if ($ttl == 2) { @@ -357,17 +347,7 @@ function hbar_graph( setup_watermark($water_mark, $water_mark_file, $water_mark_url); if (empty($chart_data)) { - return html_print_image( - $no_data_image, - true, - [ - 'width' => $width, - 'height' => $height, - 'title' => __('No data to show'), - ], - false, - true - ); + return graph_nodata_image($width, $height, 'hbar'); } if ($ttl == 2) { diff --git a/pandora_console/include/graphs/flot/jquery.flot.exportdata.pandora.js b/pandora_console/include/graphs/flot/jquery.flot.exportdata.pandora.js index 5bc3ef32b1..0b745d8ff5 100644 --- a/pandora_console/include/graphs/flot/jquery.flot.exportdata.pandora.js +++ b/pandora_console/include/graphs/flot/jquery.flot.exportdata.pandora.js @@ -159,10 +159,9 @@ if (custom_graph) { dataObject = retrieveDataOject(dataObjects,0); - //dataObjects.forEach(function (element) { - //elements.push(processDataObject(element)); - //}); - elements.push(processDataObject(dataObject)); + dataObjects.forEach(function (element) { + elements.push(processDataObject(element)); + }); graphData = elements; } else { diff --git a/pandora_console/include/graphs/flot/pandora.flot.js b/pandora_console/include/graphs/flot/pandora.flot.js index c62614ccd3..6387bf5442 100644 --- a/pandora_console/include/graphs/flot/pandora.flot.js +++ b/pandora_console/include/graphs/flot/pandora.flot.js @@ -172,7 +172,6 @@ function pandoraFlotPieCustom( show: true, radius: 5 / 8, formatter: function(label, series) { - console.log(series); return ( '
" + + (d.getHours() < 10 ? "0" : "") + + d.getHours() + ":" + - (v.getMinutes() < 10 ? "0" : "") + - v.getMinutes(); + (d.getMinutes() < 10 ? "0" : "") + + d.getMinutes(); return date_format; } } diff --git a/pandora_console/include/graphs/functions_flot.php b/pandora_console/include/graphs/functions_flot.php index 309ddf364b..eb5596cec4 100644 --- a/pandora_console/include/graphs/functions_flot.php +++ b/pandora_console/include/graphs/functions_flot.php @@ -786,6 +786,8 @@ function flot_slicesbar_graph( // Get a unique identifier to graph $graph_id = uniqid('graph_'); + $height = ((int) $height + 15); + // Set some containers to legend, graph, timestamp tooltip, etc. if ($stat_win) { $return = "
"; @@ -804,8 +806,6 @@ function flot_slicesbar_graph( $separator2 = ':,:,,,:,:'; // Transform data from our format to library format - $labels = []; - $a = []; $vars = []; $datacolor = []; @@ -819,12 +819,12 @@ function flot_slicesbar_graph( $fontsize = $config['font_size']; $fontpath = $config['fontpath']; - $extra_height = 15; + $extra_height = 40; if (defined('METACONSOLE')) { - $extra_height = 20; + $extra_height = 50; } - $return .= "
"; + $return .= ''; $maxticks = (int) 20; @@ -842,11 +842,7 @@ function flot_slicesbar_graph( $intervaltick = (int) $intervaltick; - $acumulate = 0; - $c = 0; - $acumulate_data = []; foreach ($graph_data as $label => $values) { - $labels[] = $label; $i--; foreach ($values as $key => $value) { @@ -857,19 +853,10 @@ function flot_slicesbar_graph( } $data[$jsvar][] = $value; - - $acumulate_data[$c] = $acumulate; - $acumulate += $value; - $c++; - - if ($value > $max) { - $max = $value; - } } } - // Store serialized data to use it from javascript - $labels = implode($separator, $labels); + // Store serialized data to use it from javascript. $datacolor = implode($separator, $datacolor); if (is_array($legend)) { $legend = io_safe_output(implode($separator, $legend)); @@ -881,19 +868,11 @@ function flot_slicesbar_graph( $full_legend_date = false; } - $acumulate_data = io_safe_output(implode($separator, $acumulate_data)); - - // Store data series in javascript format - $jsvars = ''; - $jsseries = []; - $date = get_system_time(); - $datelimit = (($date - $period) * 1000); + $datelimit = (($date - $period)); $i = 0; - $values2 = []; - foreach ($data as $jsvar => $values) { $values2[] = implode($separator, $values); $i ++; @@ -901,10 +880,10 @@ function flot_slicesbar_graph( $values = implode($separator2, $values2); - // Javascript code + // Javascript code. $return .= "'; diff --git a/pandora_console/include/javascript/functions_pandora_networkmap.js b/pandora_console/include/javascript/functions_pandora_networkmap.js index e5a0b87f7e..5d3477dca1 100644 --- a/pandora_console/include/javascript/functions_pandora_networkmap.js +++ b/pandora_console/include/javascript/functions_pandora_networkmap.js @@ -14,6 +14,7 @@ /* global holding_area_dimensions */ /* global networkmap_id */ /* global enterprise_installed */ +/* global networkmap_write */ /* global force */ /* global layer_graph_nodes */ /* global layer_graph_links */ @@ -2087,7 +2088,12 @@ function show_menu(item, data) { icon: "add_node", disabled: function() { if (enterprise_installed) { - return false; + // Check if user can write network maps. + if (networkmap_write) { + return false; + } else { + return true; + } } else { return true; } @@ -2099,6 +2105,14 @@ function show_menu(item, data) { items_list["center"] = { name: set_center_menu, icon: "center", + disabled: function() { + // Check if user can write network maps. + if (networkmap_write) { + return false; + } else { + return true; + } + }, callback: function(key, options) { set_center(networkmap_id); } @@ -2136,7 +2150,12 @@ function show_menu(item, data) { icon: "restart_map", disabled: function() { if (enterprise_installed) { - return false; + // Check if user can write network maps. + if (networkmap_write) { + return false; + } else { + return true; + } } else { return true; } diff --git a/pandora_console/include/javascript/openlayers.pandora.js b/pandora_console/include/javascript/openlayers.pandora.js index ae06463d95..bc4a7b99bf 100755 --- a/pandora_console/include/javascript/openlayers.pandora.js +++ b/pandora_console/include/javascript/openlayers.pandora.js @@ -87,9 +87,9 @@ function js_refreshParentLines(layerName) { { strokeWidth: 2, fillOpacity: 0.2, - fillColor: "red", + fillColor: "black", strokeDashstyle: "dash", - strokeColor: "red" + strokeColor: "black" } ); diff --git a/pandora_console/include/javascript/pandora.js b/pandora_console/include/javascript/pandora.js index 05009e7292..33ab956a1f 100644 --- a/pandora_console/include/javascript/pandora.js +++ b/pandora_console/include/javascript/pandora.js @@ -1890,6 +1890,16 @@ function load_modal(settings) { width = settings.onshow.width; } + settings.target.html("Loading modal..."); + settings.target + .dialog({ + title: "Loading", + close: false, + width: 200, + buttons: [] + }) + .show(); + $.ajax({ method: "post", url: settings.url, @@ -1898,6 +1908,9 @@ function load_modal(settings) { data: data, success: function(data) { settings.target.html(data); + if (settings.onload != undefined) { + settings.onload(data); + } settings.target.dialog({ resizable: true, draggable: true, @@ -1915,7 +1928,9 @@ function load_modal(settings) { text: settings.modal.cancel, click: function() { $(this).dialog("close"); - settings.cleanup(); + if (typeof settings.cleanup == "function") { + settings.cleanup(); + } } }, { @@ -1925,6 +1940,9 @@ function load_modal(settings) { click: function() { if (AJAX_RUNNING) return; AJAX_RUNNING = 1; + if (settings.onsubmit.preaction != undefined) { + settings.onsubmit.preaction(); + } var formdata = new FormData(); if (settings.extradata) { settings.extradata.forEach(function(item) { @@ -1952,7 +1970,9 @@ function load_modal(settings) { contentType: false, data: formdata, success: function(data) { - settings.ajax_callback(data); + if (settings.ajax_callback != undefined) { + settings.ajax_callback(data); + } AJAX_RUNNING = 0; } }); diff --git a/pandora_console/include/javascript/pandora_events.js b/pandora_console/include/javascript/pandora_events.js index 0fb6c1a6ef..79668406e1 100644 --- a/pandora_console/include/javascript/pandora_events.js +++ b/pandora_console/include/javascript/pandora_events.js @@ -63,6 +63,20 @@ function show_event_dialog(event, dialog_page, result) { height: 600 }) .show(); + $.post({ + url: "ajax.php", + data: { + page: "include/ajax/events", + get_comments: 1, + event: event, + filter: values + }, + dataType: "html", + success: function(data) { + $("#extended_event_comments_page").empty(); + $("#extended_event_comments_page").html(data); + } + }); $("#refrcounter").countdown("pause"); $("div.vc-countdown").countdown("pause"); diff --git a/pandora_console/include/lib/User.php b/pandora_console/include/lib/User.php new file mode 100644 index 0000000000..4eb5853676 --- /dev/null +++ b/pandora_console/include/lib/User.php @@ -0,0 +1,116 @@ +sessions[$data['phpsessionid']] = 1; + $info = \db_get_row_filter( + 'tsessions_php', + ['id_session' => $data['phpsessionid']] + ); + + if ($info !== false) { + // Process. + $session_data = session_decode($info['data']); + $this->idUser = $_SESSION['id_usuario']; + + // Valid session. + return $this; + } + + return null; + } + + if (isset($data['id_usuario']) === true + && isset($data['password']) === true + ) { + $user_in_db = process_user_login($user, $password, true); + if ($user_in_db !== false) { + $config['id_usuario'] = $user_in_db; + $correctLogin = true; + + // Originally at api.php. + if (session_status() === PHP_SESSION_NONE) { + session_start(); + } + + $_SESSION['id_usuario'] = $user; + session_write_close(); + + $this->idUser = $data['id_usuario']; + // Valid session. + return $this; + } + } + } + + return null; + + } + + +} diff --git a/pandora_console/include/load_session.php b/pandora_console/include/load_session.php index 39e0973287..7d06cea88d 100644 --- a/pandora_console/include/load_session.php +++ b/pandora_console/include/load_session.php @@ -91,11 +91,6 @@ function pandora_session_write($session_id, $data) { $session_id = addslashes($session_id); - // If it's an api call, the session must not be created. - if (get_parameter('op', false) && get_parameter('op2', false)) { - return true; - } - if (is_ajax()) { // Avoid session upadte while processing ajax responses - notifications. if (get_parameter('check_new_notifications', false)) { @@ -166,7 +161,7 @@ function pandora_session_gc($max_lifetime=300) if (isset($config['session_timeout'])) { $session_timeout = $config['session_timeout']; } else { - // if $config doesn`t work ... + // If $config doesn`t work ... $session_timeout = db_get_value( 'value', 'tconfig', @@ -175,9 +170,9 @@ function pandora_session_gc($max_lifetime=300) ); } - if (!empty($session_timeout)) { + if (empty($session_timeout) === false) { if ($session_timeout == -1) { - // The session expires in 10 years + // The session expires in 10 years. $session_timeout = 315576000; } else { $session_timeout *= 60; @@ -196,15 +191,14 @@ function pandora_session_gc($max_lifetime=300) ); // Deleting cron and empty sessions. - $sql = "DELETE FROM tsessions_php WHERE - data IS NULL OR id_session REGEXP '^cron-'"; + $sql = 'DELETE FROM tsessions_php WHERE data IS NULL'; db_process_sql($sql); return $retval; } -// FIXME: SAML should work with pandora session handlers +// TODO: SAML should work with pandora session handlers. if (db_get_value('value', 'tconfig', 'token', 'auth') != 'saml') { $result_handler = session_set_save_handler( 'pandora_session_open', diff --git a/pandora_console/include/styles/credential_store.css b/pandora_console/include/styles/credential_store.css index aa77985188..5707d90780 100644 --- a/pandora_console/include/styles/credential_store.css +++ b/pandora_console/include/styles/credential_store.css @@ -10,3 +10,33 @@ #new_key select { width: 60%; } + +ul.wizard li > label:not(.p-switch) { + width: auto; +} + +form.top-action-buttons ul.wizard { + display: flex; + flex-direction: row; +} + +ul.wizard li { + margin-right: 1em; +} + +form.modal ul.wizard li { + display: flex; + flex-direction: row; + width: 90%; + margin: 0 auto; + justify-items: center; +} + +form.modal ul.wizard li * { + flex: 1; +} + +ul.wizard li.flex-indep { + flex: 1; + margin: 0; +} diff --git a/pandora_console/include/styles/integriaims.css b/pandora_console/include/styles/integriaims.css new file mode 100644 index 0000000000..0c8440e739 --- /dev/null +++ b/pandora_console/include/styles/integriaims.css @@ -0,0 +1,125 @@ +/* --- Integria IMS --- */ +div.priority { + width: 80px; + color: #fff; + text-align: center; + border-radius: 5px; + padding: 5px; + display: table-cell; + vertical-align: middle; +} + +/* Details view */ +div.integria_details { + display: grid; + grid-column-gap: 10px; + grid-template-columns: repeat(3, minmax(min-content, auto)); + grid-auto-rows: 1fr; +} + +div.integria_details div.box-shadow.white_table_graph { + box-shadow: none; +} + +div.integria_details div.priority { + display: inline-block; +} + +div.integriaims_details_row { + display: grid; + grid-gap: 10px; + text-align: center; + margin-top: 8px; + margin-bottom: 8px; +} + +div.integriaims_details_titles { + font-weight: bold; +} + +div.integria_details_row_five { + grid-template-columns: repeat(5, 1fr); +} + +div.integria_details_row_three { + grid-template-columns: repeat(3, 1fr); +} + +div.integria_details_description { + width: 100%; +} + +div.integria_details_description textarea { + width: 100%; + background-color: #fbfbfb; + resize: vertical; +} + +.integriaims_details_box { + display: grid; + grid-column-gap: 10px; + grid-row-gap: 5px; + align-items: center; + width: 100%; + text-align: center; +} + +.integriaims_details_box_five { + grid-template-rows: repeat(3, 1fr); + grid-template-columns: repeat(5, 1fr); +} + +.integriaims_details_box_three { + grid-template-rows: repeat(3, 1fr); + grid-template-columns: repeat(3, 1fr); +} + +/* ui_toggles */ +.integria_details_shadow { + background-color: #fff; + border-bottom: 1px solid #e2e2e2; + border-left: 1px solid #e2e2e2; + border-top-left-radius: 5px; + border-right: 1px solid #e2e2e2; + border-top-right-radius: 5px; +} + +.integria_details_shadow .white_table_graph_header { + border-left: none; + border-right: none; +} + +.integria_details_content { + border-bottom: none; + border-left: none; + border-right: none; +} + +/* Inputs type text shown as a black line */ +.integria_incidents_options input[type="text"] { + background-color: transparent; + border: none; + border-radius: 0; + border-bottom: 1px solid #ccc; + font-family: "lato-bolder", "Open Sans", sans-serif; + font-size: 10pt; + padding: 2px 5px; + box-sizing: border-box; + background-repeat: no-repeat; + background-position: left bottom 2px; + margin-bottom: 4px; +} + +.integria_incident_options input[readonly] { + color: #848484; +} + +.comment_title { + padding: 5px 10px 5px 20px; + background-color: rgba(130, 185, 46, 0.16); + border-radius: 3px; +} + +.comment_body { + padding: 15px 20px 15px 20px; +} diff --git a/pandora_console/include/styles/login.css b/pandora_console/include/styles/login.css index 8edd7d46c0..f6c072b314 100644 --- a/pandora_console/include/styles/login.css +++ b/pandora_console/include/styles/login.css @@ -261,6 +261,7 @@ div.login_button_saml input:hover { .login_back input { background-image: url("../../images/back_login.png"); background-position: left 5% center; + background-repeat: no-repeat; } .login_back input:hover { diff --git a/pandora_console/include/styles/pandora.css b/pandora_console/include/styles/pandora.css index 8c12d11d04..459cc5c54d 100644 --- a/pandora_console/include/styles/pandora.css +++ b/pandora_console/include/styles/pandora.css @@ -452,6 +452,9 @@ select:-internal-list-box { .mw120px { min-width: 120px; } +.mw180px { + min-width: 180px; +} .mw250px { min-width: 250px; } @@ -3182,6 +3185,7 @@ table#policy_modules td * { #news_board { min-width: 530px; + width: 100%; } #right_column_logon_ok { @@ -5884,3 +5888,18 @@ table.table_modal_alternate tr td:first-child { .fullwidth { width: 100%; } + +.slicebar-box-hover-styles { + position: absolute; + background-color: #fff; + width: 80px; + height: 20px; + text-align: center; + font-family: arial, sans-serif, verdana; + padding: 3px; + border: 1px solid black; +} + +.flot-text { + width: 101%; +} diff --git a/pandora_console/include/styles/pandoraPDF.css b/pandora_console/include/styles/pandoraPDF.css index 9a55b6a1e4..4d78d5c81b 100644 --- a/pandora_console/include/styles/pandoraPDF.css +++ b/pandora_console/include/styles/pandoraPDF.css @@ -27,9 +27,6 @@ * GNU General Public License for more details. * ============================================================================ */ -table { - text-align: center; -} table.header_table { width: 100%; @@ -72,6 +69,7 @@ table.table_beauty tbody tr td { table.databox { margin-bottom: 20px; + text-align: center; } th.title_table_pdf { diff --git a/pandora_console/include/styles/wux.css b/pandora_console/include/styles/wux.css new file mode 100644 index 0000000000..cd9e3f61e2 --- /dev/null +++ b/pandora_console/include/styles/wux.css @@ -0,0 +1,10 @@ +/* + * Wux style + */ + +.wux_execution_result_transaction { + width: auto; + height: auto; + float: right; + margin-right: 200px; +} diff --git a/pandora_console/include/visual-console-client/vc.main.css b/pandora_console/include/visual-console-client/vc.main.css index 16ecacd33c..22c3cce748 100644 --- a/pandora_console/include/visual-console-client/vc.main.css +++ b/pandora_console/include/visual-console-client/vc.main.css @@ -13,27 +13,27 @@ display: flex; -webkit-box-orient: initial; -webkit-box-direction: initial; - -ms-flex-direction: initial; - flex-direction: initial; + -ms-flex-direction: initial; + flex-direction: initial; justify-items: center; -webkit-box-align: center; - -ms-flex-align: center; - align-items: center; + -ms-flex-align: center; + align-items: center; -webkit-user-select: text; - -moz-user-select: text; - -ms-user-select: text; - user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; } .visual-console-item.is-editing { border: 2px dashed #b2b2b2; -webkit-transform: translateX(-2px) translateY(-2px); - transform: translateX(-2px) translateY(-2px); + transform: translateX(-2px) translateY(-2px); cursor: move; -webkit-user-select: none; - -moz-user-select: none; - -ms-user-select: none; - user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; } .visual-console-item.is-editing > .resize-draggable { @@ -60,17 +60,17 @@ display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; - -ms-flex-direction: column; - flex-direction: column; + -ms-flex-direction: column; + flex-direction: column; -webkit-box-pack: center; - -ms-flex-pack: center; - justify-content: center; + -ms-flex-pack: center; + justify-content: center; justify-items: center; -ms-flex-line-pack: center; - align-content: center; + align-content: center; -webkit-box-align: center; - -ms-flex-align: center; - align-items: center; + -ms-flex-align: center; + align-items: center; } .visual-console-item .digital-clock > span { @@ -89,7 +89,7 @@ } .visual-console-item .digital-clock > span.timezone { - font-size: 25px; + font-size: 28px; } /* Analog clock */ @@ -100,18 +100,17 @@ .visual-console-item .analogic-clock .hour-hand { -webkit-animation: rotate-hour 43200s infinite linear; - animation: rotate-hour 43200s infinite linear; + animation: rotate-hour 43200s infinite linear; } .visual-console-item .analogic-clock .minute-hand { -webkit-animation: rotate-minute 3600s infinite linear; - animation: rotate-minute 3600s infinite linear; + animation: rotate-minute 3600s infinite linear; } .visual-console-item .analogic-clock .second-hand { -webkit-animation: rotate-second 60s infinite linear; - animation: rotate-second 60s infinite linear; + animation: rotate-second 60s infinite linear; } - -/*# sourceMappingURL=vc.main.css.map*/ \ No newline at end of file +/*# sourceMappingURL=vc.main.css.map*/ diff --git a/pandora_console/include/web2image.js b/pandora_console/include/web2image.js index bf183a73c4..8e2887aa26 100644 --- a/pandora_console/include/web2image.js +++ b/pandora_console/include/web2image.js @@ -1,5 +1,7 @@ var system = require("system"); +/* global phantom */ + if (system.args.length < 3 || system.args.length > 11) { phantom.exit(1); } @@ -14,6 +16,7 @@ var viewport_width = system.args[7]; var viewport_height = system.args[8]; var session_id = system.args[9]; var base_64 = system.args[10]; +var post_data = ""; if (!viewport_width) { viewport_width = 750; @@ -47,6 +50,29 @@ if (type_graph_pdf == "combined") { var page = require("webpage").create(); +page.onResourceError = function(resourceError) { + console.log( + "Unable to load resource (#" + + resourceError.id + + "URL:" + + resourceError.url + + ")" + ); + console.log( + "Error code: " + + resourceError.errorCode + + ". Description: " + + resourceError.errorString + ); + phantom.exit(1); +}; + +// Not supposed to be prompted messages. +page.onPrompt = function() { + console.log("Prompt message detected."); + phantom.exit(1); +}; + page.viewportSize = { width: viewport_width, height: viewport_height @@ -61,9 +87,10 @@ page.onConsoleMessage = function(msg) { page.onError = function(msg) { console.log(msg); page.close(); + phantom.exit(); }; -page.onCallback = function(st) { +page.onCallback = function() { if (!base_64) { page.render(output_filename, { format: "png" }); } else { @@ -74,4 +101,27 @@ page.onCallback = function(st) { phantom.exit(); }; -page.open(url, "POST", post_data, function(status) {}); +page.open(url, "POST", post_data, function(status) { + if (status == "fail") { + console.out("Failed to generate chart."); + phantom.exit(); + } +}); + +phantom.onError = function(msg, trace) { + var msgStack = ["PHANTOM ERROR: " + msg]; + if (trace && trace.length) { + msgStack.push("TRACE:"); + trace.forEach(function(t) { + msgStack.push( + " -> " + + (t.file || t.sourceURL) + + ": " + + t.line + + (t.function ? " (in function " + t.function + ")" : "") + ); + }); + } + console.log(msgStack.join("\n")); + phantom.exit(1); +}; diff --git a/pandora_console/index.php b/pandora_console/index.php index 74621dded1..f62a3da4cf 100755 --- a/pandora_console/index.php +++ b/pandora_console/index.php @@ -872,12 +872,6 @@ if (! isset($config['id_user'])) { $loginhash_data = get_parameter('loginhash_data', ''); $loginhash_user = str_rot13(get_parameter('loginhash_user', '')); $iduser = $_SESSION['id_usuario']; - - /* - * Check why is not available. - * logoff_db ($iduser, $_SERVER["REMOTE_ADDR"]); - */ - unset($_SESSION['id_usuario']); unset($iduser); @@ -913,7 +907,6 @@ if (! isset($config['id_user'])) { $_POST = []; $config['auth_error'] = __("User doesn\'t exist."); $iduser = $_SESSION['id_usuario']; - logoff_db($iduser, $_SERVER['REMOTE_ADDR']); unset($_SESSION['id_usuario']); unset($iduser); include_once 'general/login_page.php'; @@ -933,7 +926,6 @@ if (! isset($config['id_user'])) { $_POST = []; $config['auth_error'] = __('User only can use the API.'); $iduser = $_SESSION['id_usuario']; - logoff_db($iduser, $_SERVER['REMOTE_ADDR']); unset($_SESSION['id_usuario']); unset($iduser); include_once 'general/login_page.php'; @@ -956,7 +948,6 @@ if (file_exists(ENTERPRISE_DIR.'/load_enterprise.php')) { if (isset($_GET['bye'])) { include 'general/logoff.php'; $iduser = $_SESSION['id_usuario']; - db_logoff($iduser, $_SERVER['REMOTE_ADDR']); $_SESSION = []; session_destroy(); diff --git a/pandora_console/install.php b/pandora_console/install.php index bcf623db56..4f668fcd81 100644 --- a/pandora_console/install.php +++ b/pandora_console/install.php @@ -128,8 +128,8 @@
graph_type == 'boolean') { + $fullscale = 1; + } else { + $fullscale = 0; + } + } + ob_start(); switch ($this->graph_type) { case 'boolean': @@ -188,6 +201,7 @@ class ModuleGraph 'menu' => false, 'type_graph' => $config['type_module_charts'], 'vconsole' => true, + 'fullscale' => $fullscale, ]; $graph = grafico_modulo_sparse($params); diff --git a/pandora_console/operation/agentes/gis_view.php b/pandora_console/operation/agentes/gis_view.php index 139f8f8ae9..352b66f7af 100644 --- a/pandora_console/operation/agentes/gis_view.php +++ b/pandora_console/operation/agentes/gis_view.php @@ -97,17 +97,6 @@ echo ''; html_print_submit_button(__('Refresh path'), 'refresh', false, 'class = "sub upd" style="margin-top:0px"'); echo ''; -// Get the total number of Elements for the pagination -$sqlCount = sprintf( - 'SELECT COUNT(*) - FROM tgis_data_history - WHERE tagente_id_agente = %d AND end_timestamp > FROM_UNIXTIME(%d) - ORDER BY end_timestamp DESC', - $agentId, - (get_system_time() - $period) -); -$countData = (int) db_get_value_sql($sqlCount); - // Get the elements to present in this page switch ($config['dbtype']) { case 'mysql': @@ -147,33 +136,39 @@ switch ($config['dbtype']) { $result = db_get_all_rows_sql($sql, true); -if ($result === false) { - $sql2 = sprintf( - ' - SELECT current_longitude AS longitude, current_latitude AS latitude, current_altitude AS altitude, - start_timestamp, description, number_of_packages, manual_placement - FROM tgis_data_status - WHERE tagente_id_agente = %d - ORDER BY start_timestamp DESC - LIMIT %d OFFSET %d', - $agentId, - $config['block_size'], - (int) get_parameter('offset') - ); +$sql2 = sprintf( + ' + SELECT current_longitude AS longitude, current_latitude AS latitude, current_altitude AS altitude, + start_timestamp, description, number_of_packages, manual_placement + FROM tgis_data_status + WHERE tagente_id_agente = %d + ORDER BY start_timestamp DESC + LIMIT %d OFFSET %d', + $agentId, + $config['block_size'], + (int) get_parameter('offset') +); $result2 = db_get_all_rows_sql($sql2, true); - if ($result2 === false) { +if ($result === false && $result2 === false) { ui_print_empty_data(__('This agent doesn\'t have any GIS data.')); +} else { + if ($result === false) { + $result = $result2; } else { $result2[0]['end_timestamp'] = date('Y-m-d H:i:s'); - $result = $result2; + array_unshift($result, $result2[0]); } } + if ($result !== false) { echo '

'.__('Positional data from the last').' '.human_time_description_raw($period).'

'; + // Get the total elements for UI pagination + $countData = count($result); + if ($countData > 0) { ui_pagination($countData, false); } diff --git a/pandora_console/operation/agentes/pandora_networkmap.view.php b/pandora_console/operation/agentes/pandora_networkmap.view.php index 77f3d2c8a5..2ee34806d9 100644 --- a/pandora_console/operation/agentes/pandora_networkmap.view.php +++ b/pandora_console/operation/agentes/pandora_networkmap.view.php @@ -713,11 +713,7 @@ if (is_ajax()) { $values['options'] = json_encode($options); - $return_update = db_process_sql_update('tnetworkmap_enterprise', $values, ['id' => $id_ent_map]); - if (!$return_update) { - $return_data['ent'] = false; - break; - } + db_process_sql_update('tnetworkmap_enterprise', $values, ['id' => $id_ent_map]); } } } @@ -735,11 +731,7 @@ if (is_ajax()) { } else { $values['text_filter'] = 'migrated'; - $return_update = db_process_sql_update('tnetwork_map', $values, ['id_networkmap' => $id_open_map]); - if (!$return_update) { - $return_data['open'] = false; - break; - } + db_process_sql_update('tnetwork_map', $values, ['id_networkmap' => $id_open_map]); } } } diff --git a/pandora_console/operation/agentes/status_monitor.php b/pandora_console/operation/agentes/status_monitor.php index 0f7257663a..783c389269 100644 --- a/pandora_console/operation/agentes/status_monitor.php +++ b/pandora_console/operation/agentes/status_monitor.php @@ -1541,7 +1541,9 @@ if (!empty($result)) { $row['str_warning'], $row['max_critical'], $row['min_critical'], - $row['str_critical'] + $row['str_critical'], + $row['warning_inverse'], + $row['critical_inverse'] ); if (is_numeric($row['datos']) && !modules_is_string_type($row['module_type'])) { diff --git a/pandora_console/operation/events/events.php b/pandora_console/operation/events/events.php index 786743b8d0..bc9c59eda5 100644 --- a/pandora_console/operation/events/events.php +++ b/pandora_console/operation/events/events.php @@ -280,23 +280,27 @@ if (is_ajax()) { $events, function ($carry, $item) { $tmp = (object) $item; - $tmp->hint = ''; - $tmp->meta = false; - if (strlen($tmp->evento) >= 255) { - $tmp->hint = io_safe_output(chunk_split(substr($tmp->evento, 0, 600), 80, '
').'(...)'); - $tmp->meta = is_metaconsole(); - $tmp->evento = io_safe_output(substr($tmp->evento, 0, 253).'(...)'); - if (strpos($tmp->evento, ' ') === false) { - $tmp->evento = substr($tmp->evento, 0, 80).'(...)'; + $tmp->meta = is_metaconsole(); + if (is_metaconsole()) { + if ($tmp->server_name !== null) { + $tmp->data_server = metaconsole_get_servers($tmp->server_id); + $tmp->server_url_hash = metaconsole_get_servers_url_hash($tmp->data_server); } - } else { - $tmp->evento = io_safe_output($tmp->evento); + } + + $tmp->evento = str_replace('"', '', io_safe_output($tmp->evento)); + if (strlen($tmp->evento) >= 255) { + $tmp->evento = ui_print_truncate_text($tmp->evento, 255, $tmp->evento, true, false); } if ($tmp->module_name) { $tmp->module_name = io_safe_output($tmp->module_name); } + if ($tmp->comments) { + $tmp->comments = ui_print_comments($tmp->comments); + } + $tmp->agent_name = io_safe_output($tmp->agent_name); $tmp->ack_utimestamp = ui_print_timestamp( $tmp->ack_utimestamp, @@ -309,6 +313,8 @@ if (is_ajax()) { $tmp->data = format_numeric($tmp->data, 1); + $tmp->instructions = events_get_instructions($item); + $tmp->b64 = base64_encode(json_encode($tmp)); $carry[] = $tmp; @@ -1247,6 +1253,14 @@ try { ]; } + // Identifies column instructions to make it unsortable. + if (in_array('instructions', $fields) > 0) { + $fields[array_search('instructions', $fields)] = [ + 'text' => 'instructions', + 'class' => 'column-instructions', + ]; + } + $evento_id = array_search('evento', $fields); if ($evento_id !== false) { $fields[$evento_id] = [ @@ -1411,6 +1425,7 @@ try { 'no_sortable_columns' => [ -1, -2, + 'column-instructions', ], 'ajax_postprocess' => 'process_datatables_item(item)', 'drawCallback' => 'process_datatables_callback(this, settings)', @@ -1591,6 +1606,28 @@ function process_datatables_callback(table, settings) { function process_datatables_item(item) { + // Url to go to node from meta. + var server_url = ''; + var hashdata = ''; + if(item.meta === true){ + if(typeof item.data_server !== 'undefined' && typeof item.server_url_hash !== 'undefined'){ + server_url = item.data_server.server_url; + hashdata = item.server_url_hash; + } + } + + + // Show comments events. + item.user_comment = item.comments + + if(item.comments.length > 80){ + + item.user_comment += '  '; + item.user_comment += ' __('Show more')]); ?>'; + + } + // Grouped events. if(item.max_id_evento) { item.id_evento = item.max_id_evento @@ -1650,10 +1687,6 @@ function process_datatables_item(item) { evn += '('+item.event_rep+') '; } evn += item.evento+''; - if(item.hint !== ''){ - let ruta = item.meta == true ? '../../images/tip_help.png' : 'images/tip_help.png'; - evn += ' '+item.hint+''; - } item.mini_severity = '
'; item.mini_severity += output; @@ -1829,9 +1862,19 @@ function process_datatables_item(item) { /* Update column content now to avoid json poisoning. */ + + // Url to agent view. + var url_link = ''; + var url_link_hash = ''; + if(item.meta === true){ + url_link = server_url+'/index.php?sec=estado&sec2=operation/agentes/ver_agente&id_agente='; + url_link_hash = hashdata; + } + + /* Agent name link */ if (item.id_agente > 0) { - item.agent_name = '' + item.agent_name + ''; + item.agent_name = '' + item.agent_name + ''; } else { item.agent_name = ''; } @@ -1841,11 +1884,11 @@ function process_datatables_item(item) { - item.id_agente = '' + item.id_agente + ''; + item.id_agente = '' + item.id_agente + ''; - item.id_agente = '' + item.agent_name + ''; + item.id_agente = '' + item.agent_name + ''; @@ -2362,5 +2405,12 @@ function datetime_picker_callback() { datetime_picker_callback(); +function show_instructions(id){ + title = ""; + $('#hidden_event_instructions_' + id).dialog({ + title: title, + width: 600 + }); +} diff --git a/pandora_console/operation/incidents/configure_integriaims_incident.php b/pandora_console/operation/incidents/configure_integriaims_incident.php new file mode 100644 index 0000000000..8cf70d7848 --- /dev/null +++ b/pandora_console/operation/incidents/configure_integriaims_incident.php @@ -0,0 +1,325 @@ +width = '100%'; +$table->id = 'add_alert_table'; +$table->class = 'databox filters integria_incidents_options'; +$table->head = []; + +$table->data = []; +$table->size = []; +$table->size = []; +$table->style[0] = 'width: 33%; padding-right: 50px; padding-left: 100px;'; +$table->style[1] = 'width: 33%; padding-right: 50px; padding-left: 50px;'; +$table->style[2] = 'width: 33%; padding-right: 100px; padding-left: 50px;'; +$table->colspan[0][0] = 2; +$table->colspan[3][0] = 3; + +$help_macros = isset($_GET['from_event']) ? ui_print_help_icon('response_macros', true) : ''; + +if (isset($_GET['from_event'])) { + if ($update) { + $input_value_title = $incident_details[3]; + $input_value_type = $incident_details[17]; + $input_value_status = $incident_details[6]; + $input_value_group = $incident_details[8]; + $input_value_criticity = $incident_details[7]; + $input_value_owner = $incident_details[5]; + $input_value_content = $incident_details[4]; + } else if (isset($_GET['from_event'])) { + $input_value_title = $config['cr_incident_title']; + $input_value_type = $config['cr_incident_type']; + $input_value_status = $config['cr_incident_status']; + $input_value_group = $config['cr_default_group']; + $input_value_criticity = $config['cr_default_criticity']; + $input_value_owner = $config['cr_default_owner']; + $input_value_content = $config['cr_incident_content']; + } else { + $input_value_title = ''; + $input_value_type = ''; + $input_value_status = ''; + $input_value_group = ''; + $input_value_criticity = ''; + $input_value_owner = ''; + $input_value_content = ''; + } +} + +$table->data[0][0] = '

'.__('Title').': '.$help_macros.'

'; +$table->data[0][0] .= '
'.html_print_input_text( + 'incident_title', + $input_value_title, + __('Name'), + 50, + 100, + true, + false, + true, + '', + 'w100p' +).'
'; + +$table->data[0][2] = html_print_image('images/integria_logo_gray.png', true, ['style' => 'width: 70%; float: right;'], false); + +$table->data[1][0] = '

'.__('Type').':

'; +$table->data[1][0] .= '
'.html_print_select( + $integria_types_values, + 'type', + $input_value_type, + '', + __('Select'), + 0, + true, + false, + true, + '', + false, + 'width: 100%;' +).'
'; + +$table->data[2][0] = '

'.__('Status').':

'; +$table->data[2][0] .= '
'.html_print_select( + $integria_status_values, + 'status', + $input_value_status, + '', + __('Select'), + 1, + true, + false, + true, + '', + false, + 'width: 100%;' +).'
'; + +$table->data[1][1] = '

'.__('Group').':

'; +$table->data[1][1] .= '
'.html_print_select( + $integria_group_values, + 'group', + $input_value_group, + '', + '', + 0, + true, + false, + true, + '', + false, + 'width: 100%;' +).'
'; + +$table->data[2][1] = '

'.__('Creator').':

'; +$table->data[2][1] .= '
'.html_print_input_text( + 'creator', + $config['integria_user'], + '', + '30', + 100, + true, + true, + false, + '', + 'w100p' +).ui_print_help_tip(__('This field corresponds to the Integria IMS user specified in Integria IMS setup'), true).'
'; + +$table->data[1][2] = '

'.__('Priority').':

'; +$table->data[1][2] .= '
'.html_print_select( + $integria_criticity_values, + 'criticity', + $input_value_criticity, + '', + __('Select'), + 0, + true, + false, + true, + '', + false, + 'width: 100%;' +).'
'; + +$table->data[2][2] = '

'.__('Owner').':

'; + +$table->data[2][2] .= '
'.html_print_autocomplete_users_from_integria( + 'owner', + $input_value_owner, + true +).'
'; + +$table->data[3][0] = '

'.__('Description').': '.$help_macros.'

'; +$table->data[3][0] .= '
'.html_print_textarea( + 'incident_content', + 3, + 20, + $input_value_content, + '', + true +).'
'; + +// Print forms and stuff. +echo '
'; +html_print_table($table); + +if (!$update) { + html_print_input_hidden('create_incident', 1); +} else { + html_print_input_hidden('update_incident', 1); +} + +echo '
'; + +echo '
'; +if ($update) { + html_print_submit_button(__('Update'), 'accion', false, 'form="create_integria_incident_form" class="sub wand"'); +} else { + html_print_submit_button(__('Create'), 'accion', false, 'form="create_integria_incident_form" class="sub wand"'); +} + +echo '
'; diff --git a/pandora_console/operation/incidents/dashboard_detail_integriaims_incident.php b/pandora_console/operation/incidents/dashboard_detail_integriaims_incident.php new file mode 100644 index 0000000000..aab95b4cd7 --- /dev/null +++ b/pandora_console/operation/incidents/dashboard_detail_integriaims_incident.php @@ -0,0 +1,488 @@ +width = '100%'; +$table_files_section->id = 'files_section_table'; +$table_files_section->class = 'databox filters'; +$table_files_section->head = []; + +$table_files_section->data = []; +$table_files_section->size = []; +$table_files_section->colspan[2][0] = 3; + +// Files list table. +$table_files = new stdClass(); +$table_files->width = '100%'; +$table_files->class = 'info_table'; +$table_files->head = []; + +$table_files->head[0] = __('Filename'); +$table_files->head[1] = __('Timestamp'); +$table_files->head[2] = __('Description'); +$table_files->head[3] = __('User'); +$table_files->head[4] = __('Size'); + +if (check_acl($config['id_user'], 0, 'IW')) { + $table_files->head[5] = __('Delete'); +} + +$table_files->data = []; + +// Upload file. +if ($upload_file && ($_FILES['userfile']['name'] != '')) { + $filedescription = get_parameter('file_description', __('No description available')); + + $filename = io_safe_input($_FILES['userfile']['name']); + $filesize = io_safe_input($_FILES['userfile']['size']); + + $extension = pathinfo($filename, PATHINFO_EXTENSION); + $invalid_extensions = '/^(bat|exe|cmd|sh|php|php1|php2|php3|php4|php5|pl|cgi|386|dll|com|torrent|js|app|jar|iso| + pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess| + htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i'; + + if (!preg_match($invalid_extensions, $extension)) { + // The following is if you have clamavlib installed. + // (php5-clamavlib) and enabled in php.ini + // http://www.howtoforge.com/scan_viruses_with_php_clamavlib + if (extension_loaded('clamav')) { + cl_setlimits(5, 1000, 200, 0, 10485760); + $malware = cl_scanfile($_FILES['file']['tmp_name']); + if ($malware) { + $error = 'Malware detected: '.$malware.'
ClamAV version: '.clam_get_version(); + die($error); + // On malware, we die because it's not good to handle it + } + } + + $filecontent = base64_encode(file_get_contents($_FILES['userfile']['tmp_name'])); + + $result_api_call = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'attach_file', [$incident_id, $filename, $filesize, $filedescription, $filecontent]); + + // API method returns '0' string if success. + $file_added = ($result_api_call === '0') ? true : false; + + ui_print_result_message( + $file_added, + __('File successfully added'), + __('File could not be added') + ); + } else { + ui_print_error_message(__('File has an invalid extension')); + } +} + +// Delete file. +if (isset($_GET['delete_file'])) { + $result_api_call = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'delete_file', [$delete_file_id]); + + $file_deleted = false; + + if ($result_api_call === '0') { + $file_deleted = true; + } + + ui_print_result_message( + $file_deleted, + __('File successfully deleted'), + __('File could not be deleted') + ); +} + +// Download file. +if (isset($_GET['download_file'])) { + $file_base64 = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'download_file', [$download_file_id]); + ob_end_clean(); + + $decoded = base64_decode($file_base64); + + file_put_contents($download_file_name, $decoded); + ob_end_clean(); + + if (file_exists($download_file_name)) { + header('Content-Description: File Transfer'); + header('Content-Type: application/octet-stream'); + header('Content-Disposition: attachment; filename="'.basename($download_file_name).'"'); + header('Expires: 0'); + header('Cache-Control: must-revalidate'); + header('Pragma: public'); + header('Content-Length: '.filesize($download_file_name)); + ob_end_clean(); + readfile($download_file_name); + unlink($download_file_name); + exit; + } + + header('Location: index.php?sec=incident&sec2=operation/incidents/dashboard_detail_integriaims_incident&incident_id='.$incident_id); +} + +// Retrieve files belonging to incident and create list table. +$result_api_call = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'get_incident_files', [$incident_id]); + +if ($result_api_call != false && strlen($result_api_call) > 0) { + $files = []; + $csv_array = explode("\n", $result_api_call); + + foreach ($csv_array as $csv_line) { + if (!empty($csv_line)) { + $files[] = explode(',', $csv_line); + } + } +} + +$i = 0; + +foreach ($files as $key => $value) { + $table_files->data[$i][0] = ''.$value[11].''; + $table_files->data[$i][1] = $value[14]; + $table_files->data[$i][2] = $value[12]; + $table_files->data[$i][3] = $value[8]; + $table_files->data[$i][4] = $value[13]; + if (check_acl($config['id_user'], 0, 'IW')) { + $table_files->data[$i][5] .= ''; + $table_files->data[$i][5] .= html_print_image('images/cross.png', true, ['title' => __('Delete')]); + } + + $table_files->data[$i][5] .= ''; + + $i++; +} + +$table_files_section->data[0][0] = '

'.__('File name').':

'; +$table_files_section->data[0][0] .= html_print_input_file('userfile', true); +$table_files_section->data[1][0] = '

'.__('Description').':

'; +$table_files_section->data[1][0] .= html_print_textarea( + 'file_description', + 3, + 20, + '', + '', + true +); + +$table_files_section->data[2][0] .= '
'.html_print_submit_button(__('Upload'), 'accion', false, 'class="sub wand"', true).'
'; + +$upload_file_form = '
'; + +if (check_acl($config['id_user'], 0, 'IW')) { + $upload_file_form .= '
'.'

'.__('Add attachment').'

'.html_print_table($table_files_section, true).html_print_input_hidden('upload_file', 1, true); +} + +$upload_file_form .= '

'.__('Attached files').'

'.html_print_table($table_files, true).'
'; + +// Incident comments management. +$upload_comment = get_parameter('upload_comment'); +$comment_description = get_parameter('comment_description'); + +// Comments section table. +$table_comments_section = new stdClass(); +$table_comments_section->width = '100%'; +$table_comments_section->id = 'files_section_table'; +$table_comments_section->class = 'databox filters'; +$table_comments_section->head = []; + +$table_comments_section->data = []; +$table_comments_section->size = []; + +// Comments list table. +$table_comments = new stdClass(); +$table_comments->width = '100%'; +$table_comments->class = 'info_table'; +$table_comments->head = []; + +$table_comments->head[0] = __('Filename'); +$table_comments->head[1] = __('Timestamp'); +$table_comments->head[2] = __('Description'); +$table_comments->head[3] = __('User'); +$table_comments->head[4] = __('Size'); +$table_comments->head[5] = __('Delete'); + +$table_comments->data = []; + +$comment_disabled = ($array_get_incidents[6] == 7); + +if ($comment_disabled === true) { + $attribute = 'disabled=disabled'; +} + +$table_comments_section->data[0][0] = '

'.__('Description').':

'; +$table_comments_section->data[0][0] .= html_print_textarea( + 'comment_description', + 3, + 20, + '', + $attribute, + true +); + +$table_comments_section->data[1][1] .= '
'.html_print_submit_button(__('Add'), 'accion', $comment_disabled, 'class="sub wand"', true).'
'; + +// Upload comment. If ticket is closed, this action cannot be performed. +if ($upload_comment && $array_get_incidents[6] != 7) { + $result_api_call = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'create_workunit', [$incident_id, $comment_description, '0.00', 0, 1, '0']); + + // API method returns id of new comment if success. + $comment_added = ($result_api_call >= '0') ? true : false; + + ui_print_result_message( + $comment_added, + __('Comment successfully added'), + __('Comment could not be added') + ); +} + +// Retrieve comments belonging to incident and create comments table. +$result_api_call = integria_api_call($config['integria_hostname'], $config['integria_user'], $config['integria_pass'], $config['integria_api_pass'], 'get_incident_workunits', [$incident_id]); + +if ($result_api_call != false && strlen($result_api_call) > 0) { + $comments = []; + $csv_array = explode("\n", $result_api_call); + + foreach ($csv_array as $csv_line) { + if (!empty($csv_line)) { + $comments[] = explode(',', $csv_line); + } + } +} + +$comment_table = ''; + +if (!empty($comments)) { + foreach ($comments as $key => $value) { + $comment_table .= '
'.$value[3].' said '.$value[1].''.$value[2].' Hours
'; + $comment_table .= '
'.$value[4].'
'; + } +} else { + $comment_table = __('No comments found'); +} + +$upload_comment_form = '
'; + +if (check_acl($config['id_user'], 0, 'IW')) { + $upload_comment_form .= '

'.__('Add comment').'

'.html_print_table($table_comments_section, true).html_print_input_hidden('upload_comment', 1, true).'
'; +} + +$upload_comment_form .= '

'.__('Comments').'

'.$comment_table.'
'; + +// Details box. +$details_box = '
'; +$details_box .= ' +
'.__('Status').'
+
'.__('Resolution').'
+
'.__('Group').'
+
'.__('Priority').'
+
'.__('Type').'
'; +$details_box .= ' +
'.html_print_image('images/heart.png', true).'
+
'.html_print_image('images/builder.png', true).'
+
'.html_print_image('images/user_green.png', true).'
+
'.ui_print_integria_incident_priority($priority, $priority_text).'
+
'.html_print_image('images/incidents.png', true).'
'; +$details_box .= ' +
'.$status_text.'
+
'.$resolution_text.'
+
'.$group_text.'
+
'.$priority_text.'
+
'.$type_text.'
'; +$details_box .= '
'; + + +// People box. +$people_box = '
'; +$people_box .= ' +
'.html_print_image('images/header_user_green.png', true, ['width' => '21']).'
+
'.html_print_image('images/header_user_green.png', true, ['width' => '21']).'
+
'.html_print_image('images/header_user_green.png', true, ['width' => '21']).'
'; +$people_box .= ' +
'.__('Created by').':
+
'.__('Owned by').':
+
'.__('Closed by').':
'; +$people_box .= ' +
'.$creator.'
+
'.$owner.'
+
'.$closed_by.'
'; +$people_box .= '
'; + + +// Dates box. +$dates_box = '
'; +$dates_box .= ' +
'.html_print_image('images/tick.png', true).'
+
'.html_print_image('images/update.png', true, ['width' => '21']).'
+
'.html_print_image('images/mul.png', true).'
'; +$dates_box .= ' +
'.__('Created at').':
+
'.__('Updated at').':
+
'.__('Closed at').':
'; +$dates_box .= ' +
'.$created_at.'
+
'.$updated_at.'
+
'.$closed_at.'
'; +$dates_box .= '
'; + + +// Show details, people and dates. +echo '
'; + ui_toggle($details_box, __('Details'), '', 'details_box', false, false, '', 'integria_details_content white-box-content', 'integria_details_shadow box-shadow white_table_graph'); + ui_toggle($people_box, __('People'), '', 'people_box', false, false, '', 'integria_details_content white-box-content', 'integria_details_shadow box-shadow white_table_graph'); + ui_toggle($dates_box, __('Dates'), '', 'dates_box', false, false, '', 'integria_details_content white-box-content', 'integria_details_shadow box-shadow white_table_graph'); +echo '
'; + + // Show description. +$description_box = '
'.html_print_textarea( + 'integria_details_description', + 3, + 0, + $description, + 'disabled="disabled"', + true +).'
'; +ui_toggle($description_box, __('Description'), '', '', false); + +echo '
'; +ui_toggle( + $upload_file_form, + __('Attached files'), + '', + '', + true, + false, + 'white_box white_box_opened', + 'no-border flex' +); +echo '
'; + +echo '
'; +ui_toggle( + $upload_comment_form, + __('Comments'), + '', + '', + true, + false, + 'white_box white_box_opened', + 'no-border flex' +); +echo '
'; + +?> + \ No newline at end of file diff --git a/pandora_console/operation/incidents/integriaims_export_csv.php b/pandora_console/operation/incidents/integriaims_export_csv.php new file mode 100644 index 0000000000..03a038e58a --- /dev/null +++ b/pandora_console/operation/incidents/integriaims_export_csv.php @@ -0,0 +1,129 @@ + $value) { + // Status. + if ($tickets_csv_array[$key][6] == 0) { + $tickets_csv_array[$key][6] = 'None'; + } else { + $tickets_csv_array[$key][6] = $status_incident[$tickets_csv_array[$key][6]]; + } + + // Priority. + $tickets_csv_array[$key][7] = $priority_incident[$tickets_csv_array[$key][7]]; + + // Group. + $tickets_csv_array[$key][8] = $group_incident[$tickets_csv_array[$key][8]]; + + // Resolution. + if ($tickets_csv_array[$key][12] == 0) { + $tickets_csv_array[$key][12] = 'None'; + } else { + $tickets_csv_array[$key][12] = $resolution_incident[$tickets_csv_array[$key][12]]; + } + + $tickets_csv_array_filter[$key] = [ + 'id_incidencia' => $tickets_csv_array[$key][0], + 'titulo' => $tickets_csv_array[$key][3], + 'id_grupo' => $tickets_csv_array[$key][8], + 'estado' => $tickets_csv_array[$key][6], + 'resolution' => $tickets_csv_array[$key][12], + 'prioridad' => $tickets_csv_array[$key][7], + 'actualizacion' => $tickets_csv_array[$key][9], + 'inicio' => $tickets_csv_array[$key][1], + 'id_creator' => $tickets_csv_array[$key][10], + 'owner' => $tickets_csv_array[$key][5], + ]; +} + +// Header for CSV file. +$header = [ + __('ID Ticket'), + __('Title'), + __('Group/Company'), + __('Status'), + __('Resolution'), + __('Priority'), + __('Updated'), + __('Started'), + __('Creator'), + __('Owner'), +]; + +$header_csv = ''; +foreach ($header as $key => $value) { + $header_csv .= $value.','; +} + +$header_csv = io_safe_output($header_csv).PHP_EOL; + + +// Join header and content. +$tickets_csv = ''; +foreach ($tickets_csv_array_filter as $key => $value) { + $tickets_csv .= implode(',', $tickets_csv_array_filter[$key]).PHP_EOL; +} + +$tickets_csv = $header_csv.$tickets_csv; + + +// Create csv file. +$filename = 'tickets_export-'.date('Ymd').'-'.date('His').'.csv'; + +ob_clean(); + +header('Content-Type: text/csv; charset=utf-8'); +header('Content-Disposition: attachment; filename='.$filename); + +// BOM. +echo pack('C*', 0xEF, 0xBB, 0xBF); + +// CSV file. +echo io_safe_output($tickets_csv); diff --git a/pandora_console/operation/incidents/list_integriaims_incidents.php b/pandora_console/operation/incidents/list_integriaims_incidents.php new file mode 100644 index 0000000000..d97276c15e --- /dev/null +++ b/pandora_console/operation/incidents/list_integriaims_incidents.php @@ -0,0 +1,335 @@ +width = '100%'; +$table->class = 'databox filters'; +$table->styleTable = 'margin-bottom:0px'; +$table->cellpadding = '0'; +$table->cellspacing = '0'; +$table->data = []; + +$table->data[0][0] = __('Text filter'); +$table->data[0][1] = html_print_input_text('incident_text', $incident_text, '', 30, 100, true); + +$table->data[0][2] = __('Status'); +$table->data[0][3] = html_print_select( + $status_incident, + 'incident_status', + $incident_status, + '', + __('All'), + 0, + true +); + +$table->data[0][4] = __('Group'); +$table->data[0][5] = html_print_select( + $group_incident, + 'incident_group', + $incident_group, + '', + __('All'), + 1, + true +); + +$table->data[1][0] = __('Owner'); +$table->data[1][1] = html_print_autocomplete_users_from_integria('incident_owner', $incident_owner, true); + +$table->data[1][2] = __('Creator'); +$table->data[1][3] = html_print_autocomplete_users_from_integria('incident_creator', $incident_creator, true); + +$table->data[1][4] = __('Priority'); +$table->data[1][5] = html_print_select( + $priority_incident, + 'incident_priority', + $incident_priority, + '', + __('All'), + -1, + true +); + +$table->data[2][0] = __('Resolution'); +$table->data[2][1] = html_print_select( + $resolution_incident, + 'incident_resolution', + $incident_resolution, + '', + __('All'), + '', + true +); + +// TODO: field type date. +$table->data[2][2] = __('Date'); +$table->data[2][3] = html_print_input_text_extended( + 'created_from', + $created_from, + 'created_from', + '', + 12, + 50, + false, + '', + 'placeholder="'.__('Created from').'"', + true +); +$table->data[2][3] .= html_print_input_text_extended( + 'created_to', + $created_to, + 'created_to', + '', + 12, + 50, + false, + '', + 'style="margin-left:5px;" placeholder="'.__('Created to').'"', + true +); + +// TODO: image of Integria IMS. +$table->data[2][4] = ''; +$table->data[2][5] = ''; + + +// Send filters to get_tickets_integriaims(). +$tickets_filters = [ + 'incident_text' => $incident_text, + 'incident_status' => $incident_status, + 'incident_group' => $incident_group, + 'incident_owner' => $incident_owner, + 'incident_creator' => $incident_creator, + 'incident_priority' => $incident_priority, + 'incident_resolution' => $incident_resolution, + 'created_from' => $created_from, + 'created_to' => $created_to, +]; + +// Data to export to csv file. +$decode_csv = base64_encode(json_encode($tickets_filters)); + + +// ---- PRINT TABLE FILTERS ---- +$integria_incidents_form = '
'; +$integria_incidents_form .= html_print_table($table, true); +$integria_incidents_form .= '
'; +$integria_incidents_form .= '
'.html_print_button( + __('Export to CSV'), + 'csv_export', + false, + "location.href='operation/incidents/integriaims_export_csv.php?tickets_filters=$decode_csv'", + 'class="sub next"', + true +).'
'; +$integria_incidents_form .= '
'.html_print_submit_button(__('Filter'), 'filter_button', false, 'class="sub filter"', true).'
'; +$integria_incidents_form .= '
'; +$integria_incidents_form .= '
'; + +ui_toggle($integria_incidents_form, __('Filter'), '', '', false); + +/* + * Order api call 'get_incidents'. + * + * resolution = $array_get_incidents[$key][12] + * id_incidencia = $array_get_incidents[$key][0] + * titulo = $array_get_incidents[$key][3] + * id_grupo = $array_get_incidents[$key][8] + * estado = $array_get_incidents[$key][6] + * prioridad = $array_get_incidents[$key][7] + * actualizacion = $array_get_incidents[$key][9] + * id_creator = $array_get_incidents[$key][10] + * + */ + +// ---- LIST OF INCIDENTS ---- +// Get list of incidents. +$array_get_incidents = get_tickets_integriaims($tickets_filters); + +// Prepare pagination. +$incidents_limit = $config['block_size']; +$incidents_paginated = array_slice($array_get_incidents, $offset, $incidents_limit, true); + +// TABLE INCIDENTS. +$table = new stdClass(); +$table->width = '100%'; +$table->class = 'info_table'; +$table->head = []; + +$table->head[0] = __('ID'); +$table->head[1] = __('Ticket'); +$table->head[2] = __('Group/Company'); +$table->head[3] = __('Status/Resolution'); +$table->head[4] = __('Prior'); +$table->head[5] = __('Updated/Started'); +$table->head[6] = __('Creator'); +$table->head[7] = __('Owner'); +if (check_acl($config['id_user'], 0, 'IW') || check_acl($config['id_user'], 0, 'IM')) { + $table->head[8] = ''; +} + +$table->data = []; +$i = 0; + +foreach ($incidents_paginated as $key => $value) { + if ($array_get_incidents[$key][6] == 0) { + $status_incident[$array_get_incidents[$key][6]] = __('None'); + } + + if ($array_get_incidents[$key][12] == 0) { + $resolution_incident[$array_get_incidents[$key][12]] = __('None'); + } + + $table->data[$i][0] = '#'.$array_get_incidents[$key][0]; + $table->data[$i][1] = ''; + $table->data[$i][1] .= $array_get_incidents[$key][3]; + $table->data[$i][1] .= ''; + $table->data[$i][2] = $group_incident[$array_get_incidents[$key][8]]; + $table->data[$i][3] = $status_incident[$array_get_incidents[$key][6]].' / '.$resolution_incident[$array_get_incidents[$key][12]]; + $table->data[$i][4] = ui_print_integria_incident_priority($array_get_incidents[$key][7], $priority_incident[$array_get_incidents[$key][7]]); + $table->data[$i][5] = $array_get_incidents[$key][9].' / '.$array_get_incidents[$key][1]; + $table->data[$i][6] = $array_get_incidents[$key][10]; + $table->data[$i][7] = $array_get_incidents[$key][5]; + $table->data[$i][8] = ''; + $table->cellclass[$i][8] = 'action_buttons'; + if (check_acl($config['id_user'], 0, 'IW')) { + $table->data[$i][8] .= ''; + $table->data[$i][8] .= html_print_image('images/config.png', true, ['title' => __('Edit')]); + $table->data[$i][8] .= ''; + } + + if (check_acl($config['id_user'], 0, 'IM')) { + $table->data[$i][8] .= ''; + $table->data[$i][8] .= html_print_image('images/cross.png', true, ['title' => __('Delete')]); + $table->data[$i][8] .= ''; + } + + $i++; +} + +// Show table incidents. +ui_pagination(count($array_get_incidents), $url, $offset); +if (empty($table->data) === true) { + ui_print_info_message(['no_close' => true, 'message' => __('No tickets to show').'.' ]); +} else { + html_print_table($table); + ui_pagination(count($array_get_incidents), $url, $offset, 0, false, 'offset', true, 'pagination-bottom'); +} + +// Show button to create incident. +if (check_acl($config['id_user'], 0, 'IR')) { + echo '
'; + echo '
'; + html_print_submit_button(__('Create'), 'create_new_incident', false, 'class="sub next"'); + echo '
'; + echo '
'; +} + +// Datapicker library for show calendar. +ui_require_jquery_file('ui.datepicker-'.get_user_language(), 'include/javascript/i18n/'); +?> + + + \ No newline at end of file diff --git a/pandora_console/operation/menu.php b/pandora_console/operation/menu.php index 936cb6a814..58213ed8ee 100644 --- a/pandora_console/operation/menu.php +++ b/pandora_console/operation/menu.php @@ -479,6 +479,7 @@ if (check_acl($config['id_user'], 0, 'IR') $sub2 = []; $sub2['operation/incidents/incident']['text'] = __('List of Incidents'); $sub2[$sec2sub]['text'] = __('Statistics'); + $sub2['operation/incidents/list_integriaims_incidents']['text'] = __('Integria IMS Tickets'); $sub[$sec2]['sub2'] = $sub2; $sec2 = $temp_sec2; diff --git a/pandora_console/operation/reporting/reporting_viewer.php b/pandora_console/operation/reporting/reporting_viewer.php index e8431ddeb2..7528f15253 100755 --- a/pandora_console/operation/reporting/reporting_viewer.php +++ b/pandora_console/operation/reporting/reporting_viewer.php @@ -17,7 +17,6 @@ global $config; check_login(); enterprise_hook('open_meta_frame'); - $id_report = (int) get_parameter('id'); if (! $id_report) { @@ -125,7 +124,7 @@ if (!defined('METACONSOLE')) { } // Page header for metaconsole -if ($config['metaconsole'] == 1 and defined('METACONSOLE')) { +if (is_metaconsole()) { // Bread crumbs ui_meta_add_breadcrumb(['link' => 'index.php?sec=reporting&sec2=godmode/reporting/reporting_builder', 'text' => __('Reporting')]); diff --git a/pandora_console/operation/search_policies.getdata.php b/pandora_console/operation/search_policies.getdata.php index 5186f1f0a9..1274b17076 100644 --- a/pandora_console/operation/search_policies.getdata.php +++ b/pandora_console/operation/search_policies.getdata.php @@ -18,6 +18,11 @@ enterprise_include_once('include/functions_policies.php'); $searchpolicies = check_acl($config['id_user'], 0, 'AW'); +if (!$searchpolicies) { + $totalPolicies = 0; + return; +} + $selectpolicieIDUp = ''; $selectpolicieIDDown = ''; $selectNameUp = ''; @@ -169,7 +174,7 @@ switch ($sortField) { break; } -if ($searchpolicies == 0) { +if ($searchpolicies) { /* We take the user groups to get policies that meet the requirements of the search and which the user have permission on this groups @@ -189,6 +194,7 @@ if ($searchpolicies == 0) { $policies = db_process_sql($sql); + if ($policies !== false) { $totalPolicies = count($policies); diff --git a/pandora_console/operation/search_results.php b/pandora_console/operation/search_results.php index 803a92cdd1..b856f5f14e 100644 --- a/pandora_console/operation/search_results.php +++ b/pandora_console/operation/search_results.php @@ -18,7 +18,7 @@ require_once $config['homedir'].'/include/functions_reporting.php'; enterprise_include('operation/reporting/custom_reporting.php'); $searchAgents = $searchAlerts = $searchModules = check_acl($config['id_user'], 0, 'AR'); -$searchUsers = $searchPolicies = check_acl($config['id_user'], 0, 'AW'); +$searchUsers = $searchPolicies = check_acl($config['id_user'], 0, 'AR'); $searchMaps = $searchReports = $searchGraphs = check_acl($config['id_user'], 0, 'IR'); $searchMain = true; $searchHelps = true; diff --git a/pandora_console/operation/search_users.getdata.php b/pandora_console/operation/search_users.getdata.php index a39cdf70f1..5e67c90059 100644 --- a/pandora_console/operation/search_users.getdata.php +++ b/pandora_console/operation/search_users.getdata.php @@ -18,6 +18,10 @@ require_once $config['homedir'].'/include/functions_users.php'; require_once $config['homedir'].'/include/functions_groups.php'; $searchUsers = check_acl($config['id_user'], 0, 'UM'); +if (!$searchUsers) { + $totalUsers = 0; + return; +} $selectUserIDUp = ''; $selectUserIDDown = ''; diff --git a/pandora_console/operation/search_users.php b/pandora_console/operation/search_users.php index 8014d5a261..b2232a44f9 100755 --- a/pandora_console/operation/search_users.php +++ b/pandora_console/operation/search_users.php @@ -91,7 +91,7 @@ if (!$users || !$searchUsers) { } echo '
'; - ui_pagination($totalUsers); + // ui_pagination($totalUsers); html_print_table($table); unset($table); ui_pagination($totalUsers); diff --git a/pandora_console/operation/snmpconsole/snmp_view.php b/pandora_console/operation/snmpconsole/snmp_view.php index 677a7a625a..72f24e0575 100755 --- a/pandora_console/operation/snmpconsole/snmp_view.php +++ b/pandora_console/operation/snmpconsole/snmp_view.php @@ -956,7 +956,8 @@ if ($traps !== false) { } } else { $agent_trap_group = db_get_value('id_grupo', 'tagente', 'nombre', $trap['source']); - if ((check_acl($config['id_user'], $agent_trap_group, 'AW'))) { + + if ((check_acl($config['id_user'], $agent_trap_group, 'IM'))) { $data[8] .= ''.html_print_image('images/cross.png', true, ['border' => '0', 'title' => __('Delete')]).' '; } } diff --git a/pandora_console/operation/users/user_edit.php b/pandora_console/operation/users/user_edit.php index b8b42ad945..fcc719dfaa 100644 --- a/pandora_console/operation/users/user_edit.php +++ b/pandora_console/operation/users/user_edit.php @@ -333,7 +333,7 @@ $id_usr = $config['id_user']; if (!$meta) { - $home_screen = '

'.__('Home screen').ui_print_help_tip(__('User can customize the home page. By default, will display \'Agent Detail\'. Example: Select \'Other\' and type sec=estado&sec2=operation/agentes/estado_agente to show agent detail view'), true).'

'; + $home_screen = '

'.__('Home screen').ui_print_help_tip(__('User can customize the home page. By default, will display \'Agent Detail\'. Example: Select \'Other\' and type index.php?sec=estado&sec2=operation/agentes/ver_agente&id_agente=1 to show agent detail view'), true).'

'; $values = [ 'Default' => __('Default'), 'Visual console' => __('Visual console'), @@ -462,6 +462,8 @@ $autorefresh_list_out['operation/agentes/status_monitor'] = 'Monitor detail'; $autorefresh_list_out['enterprise/operation/services/services'] = 'Services'; $autorefresh_list_out['enterprise/dashboard/main_dashboard'] = 'Dashboard'; $autorefresh_list_out['operation/reporting/graph_viewer'] = 'Graph Viewer'; +$autorefresh_list_out['operation/gis_maps/render_view'] = 'Gis Map'; + $autorefresh_list_out['operation/snmpconsole/snmp_view'] = 'SNMP console'; $autorefresh_list_out['operation/agentes/pandora_networkmap'] = 'Network map'; $autorefresh_list_out['operation/visual_console/render_view'] = 'Visual console'; @@ -1150,7 +1152,7 @@ function ehorus_connection_test(host, port) { var user = $('input#text-ehorus_user_level_user').val(); var pass = $('input#password-ehorus_user_level_pass').val(); - debugger; + var badRequestMessage = ''; var notFoundMessage = ''; var invalidPassMessage = ''; diff --git a/pandora_console/operation/visual_console/legacy_public_view.php b/pandora_console/operation/visual_console/legacy_public_view.php index 7bea2a22c9..ab6def4f70 100644 --- a/pandora_console/operation/visual_console/legacy_public_view.php +++ b/pandora_console/operation/visual_console/legacy_public_view.php @@ -115,6 +115,7 @@ echo ''; // Countdown. echo '
  • '; echo '
    '; +echo '
    '; echo '
    '; echo __('Refresh').':'; echo html_print_select( @@ -187,7 +188,7 @@ $ignored_params['refr'] = ''; var controls = document.getElementById('vc-controls'); autoHideElement(controls, 1000); - $('select#refr').change(function (event) { + $('#vc-controls').change(function (event) { refr = Number.parseInt(event.target.value, 10); startCountDown(refr, false); }); diff --git a/pandora_console/pandora_console.redhat.spec b/pandora_console/pandora_console.redhat.spec index e72aa4fa98..a662559b87 100644 --- a/pandora_console/pandora_console.redhat.spec +++ b/pandora_console/pandora_console.redhat.spec @@ -2,8 +2,8 @@ # Pandora FMS Console # %define name pandorafms_console -%define version 7.0NG.738 -%define release 190913 +%define version 7.0NG.740 +%define release 191029 # User and Group under which Apache is running %define httpd_name httpd diff --git a/pandora_console/pandora_console.rhel7.spec b/pandora_console/pandora_console.rhel7.spec index 1b2607b739..91f5bebedf 100644 --- a/pandora_console/pandora_console.rhel7.spec +++ b/pandora_console/pandora_console.rhel7.spec @@ -2,8 +2,8 @@ # Pandora FMS Console # %define name pandorafms_console -%define version 7.0NG.738 -%define release 190913 +%define version 7.0NG.740 +%define release 191029 # User and Group under which Apache is running %define httpd_name httpd diff --git a/pandora_console/pandora_console.spec b/pandora_console/pandora_console.spec index 29e49dfa69..1aa902495e 100644 --- a/pandora_console/pandora_console.spec +++ b/pandora_console/pandora_console.spec @@ -2,8 +2,8 @@ # Pandora FMS Console # %define name pandorafms_console -%define version 7.0NG.738 -%define release 190913 +%define version 7.0NG.740 +%define release 191029 %define httpd_name httpd # User and Group under which Apache is running %define httpd_name apache2 diff --git a/pandora_console/pandora_console_install b/pandora_console/pandora_console_install index bda06177d6..34fc8cd0b6 100644 --- a/pandora_console/pandora_console_install +++ b/pandora_console/pandora_console_install @@ -9,7 +9,7 @@ # This code is licensed under GPL 2.0 license. # ********************************************************************** -PI_VERSION="7.0NG.738" +PI_VERSION="7.0NG.740" FORCE=0 DESTDIR="" LOG_TIMESTAMP=`date +"%Y/%m/%d %H:%M:%S"` diff --git a/pandora_console/pandoradb.sql b/pandora_console/pandoradb.sql index d1de66ab07..3b11dccb4d 100644 --- a/pandora_console/pandoradb.sql +++ b/pandora_console/pandoradb.sql @@ -1455,6 +1455,7 @@ CREATE TABLE IF NOT EXISTS `treport_content` ( `current_month` TINYINT(1) DEFAULT '1', `failover_mode` tinyint(1) DEFAULT '1', `failover_type` tinyint(1) DEFAULT '1', + `uncompressed_module` TINYINT DEFAULT '0', PRIMARY KEY(`id_rc`), FOREIGN KEY (`id_report`) REFERENCES treport(`id_report`) ON UPDATE CASCADE ON DELETE CASCADE @@ -2438,14 +2439,17 @@ CREATE TABLE IF NOT EXISTS `tdashboard` ( -- Table `tdatabase` -- --------------------------------------------------------------------- CREATE TABLE IF NOT EXISTS `tdatabase` ( - `id` int(10) unsigned NOT NULL auto_increment, - `host` varchar(100) default '', - `os_port` int(4) unsigned default '22', - `os_user` varchar(100) default '', - `db_port` int(4) unsigned default '3306', + `id` INT(10) unsigned NOT NULL auto_increment, + `host` VARCHAR(255) default '', + `label` VARCHAR(255) default '', + `os_port` INT UNSIGNED NOT NULL DEFAULT 22, + `os_user` VARCHAR(255) default '', + `db_port` INT UNSIGNED NOT NULL DEFAULT 3306, `status` tinyint(1) unsigned default '0', `action` tinyint(1) unsigned default '0', - `last_error` varchar(255) default '', + `ssh_key` TEXT, + `ssh_pubkey` TEXT, + `last_error` TEXT, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARSET=utf8 ; @@ -2998,6 +3002,7 @@ CREATE TABLE IF NOT EXISTS `treport_content_template` ( `current_month` TINYINT(1) DEFAULT '1', `failover_mode` tinyint(1) DEFAULT '1', `failover_type` tinyint(1) DEFAULT '1', + `uncompressed_module` TINYINT DEFAULT '0', PRIMARY KEY(`id_rc`) ) ENGINE = InnoDB DEFAULT CHARSET=utf8; @@ -3517,6 +3522,7 @@ CREATE TABLE IF NOT EXISTS `tlayout_template_data` ( `time_format` varchar(60) NOT NULL default "time", `timezone` varchar(60) NOT NULL default "Europe/Madrid", `show_last_value` tinyint(1) UNSIGNED NULL default '0', + `cache_expiration` INTEGER UNSIGNED NOT NULL default 0, PRIMARY KEY(`id`), FOREIGN KEY (`id_layout_template`) REFERENCES tlayout_template(`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE = InnoDB DEFAULT CHARSET=utf8; diff --git a/pandora_console/pandoradb_data.sql b/pandora_console/pandoradb_data.sql index a02f88fe5f..56be11251e 100644 --- a/pandora_console/pandoradb_data.sql +++ b/pandora_console/pandoradb_data.sql @@ -109,14 +109,37 @@ INSERT INTO `tconfig` (`token`, `value`) VALUES ('custom_report_front_logo', 'images/pandora_logo_white.jpg'), ('custom_report_front_header', ''), ('custom_report_front_footer', ''), -('MR', 31), +('MR', 32), ('identification_reminder', 1), ('identification_reminder_timestamp', 0), -('current_package_enterprise', '738'), +('current_package_enterprise', '740'), ('post_process_custom_values', '{"0.00000038580247":"Seconds to months","0.00000165343915":"Seconds to weeks","0.00001157407407":"Seconds to days","0.01666666666667":"Seconds to minutes","0.00000000093132":"Bytes to Gigabytes","0.00000095367432":"Bytes to Megabytes","0.0009765625":"Bytes to Kilobytes","0.00000001653439":"Timeticks to weeks","0.00000011574074":"Timeticks to days"}'), ('custom_docs_logo', 'default_docs.png'), ('custom_support_logo', 'default_support.png'), -('custom_logo_white_bg_preview', 'pandora_logo_head_white_bg.png'); +('custom_logo_white_bg_preview', 'pandora_logo_head_white_bg.png'), +('integria_enabled', 0), +('integria_user', ''), +('integria_pass', ''), +('integria_hostname', ''), +('integria_api_pass', ''), +('integria_req_timeout', 5), +('default_group', ''), +('default_criticity', ''), +('default_creator', ''), +('default_owner', ''), +('incident_type', ''), +('incident_status', ''), +('incident_title', ''), +('incident_content', ''), +('cr_default_group', ''), +('cr_default_criticity', ''), +('cr_default_creator', ''), +('cr_default_owner', ''), +('cr_incident_type', ''), +('cr_incident_status', ''), +('cr_incident_title', ''), +('cr_incident_content', ''), +('sample_agent', '0'); UNLOCK TABLES; -- @@ -1317,7 +1340,8 @@ UPDATE `tnotification_source` SET `enabled`=1 WHERE `description` = 'System -- INSERT INTO `tlayout` VALUES - (1, 'Demo visual console', 0, 'fondo.jpg', 1080, 1920, 'white', 0); + (1, 'Demo visual console', 0, 'fondo.jpg', 1080, 1920, 'white', 0), + (2,'Demo visual console 2',0,'fondo-keep-alive.jpg',1080,1920,'#FFF',0); -- -- Dumping data for table `tlayout_data` @@ -1379,46 +1403,63 @@ VALUES (53,1,1413,243,205,426,'','rack_frame',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (54,1,962,381,73,408,'','rack_firewall',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (55,1,962,454,73,408,'','rack_pdu',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (56,1,530,732,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (57,1,962,233,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (58,1,962,307,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (59,1,530,658,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (60,1,530,350,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (61,1,530,204,73,408,'','rack_psa',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (62,1,530,277,73,408,'','rack_pdu',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (63,1,530,585,73,408,'','rack_firewall',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (64,1,530,424,161,411,'','rack_double_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), + (56,1,530,732,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (57,1,962,233,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (58,1,962,307,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (59,1,530,658,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (60,1,530,350,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (61,1,530,204,73,408,'','rack_psa',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (62,1,530,277,73,408,'','rack_pdu',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (63,1,530,585,73,408,'','rack_firewall',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (64,1,530,424,161,411,'','rack_double_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), (65,1,1426,448,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (66,1,1495,540,174,29,'','rack_server_rack',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (67,1,1423,260,174,29,'','rack_server_rack',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (68,1,1463,540,174,29,'','rack_server_rack',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (69,1,1433,540,174,29,'','rack_server_rack',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (70,1,74,733,73,408,'','rack_pdu',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), + (70,1,74,733,73,408,'','rack_pdu',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), (71,1,1098,701,80,18,'','rack_hard_disk',0,3600,9,2,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (72,1,1148,701,80,18,'','rack_hard_disk',0,3600,9,2,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (73,1,1340,699,80,18,'','rack_hard_disk_2',0,3600,9,2,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (74,1,1358,783,80,18,'','rack_hard_disk_2',0,3600,9,2,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (75,1,1358,699,80,18,'','rack_hard_disk_2',0,3600,9,2,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (76,1,1143,783,80,18,'','rack_hard_disk',0,3600,9,2,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (77,1,962,682,205,426,'','rack_frame',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), + (77,1,962,682,205,426,'','rack_frame',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), (78,1,1522,540,174,29,'','rack_server_rack',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (79,1,1419,521,205,426,'','rack_frame',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (80,1,74,278,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (81,1,74,572,161,411,'','rack_double_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), + (79,1,1420,521,205,426,'','rack_frame',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (80,1,74,278,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (81,1,74,572,161,411,'','rack_double_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), (82,1,1418,729,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (83,1,962,527,73,408,'','rack_switch',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (84,1,74,352,73,408,'','rack_router',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (85,1,962,600,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (86,1,530,806,73,408,'','rack_firewall',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (87,1,74,425,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), + (86,1,530,806,73,408,'','rack_firewall',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (87,1,74,425,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), (88,1,74,499,73,408,'','rack_switch',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (89,1,74,806,73,408,'','rack_psa',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), - (90,1,74,204,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), + (89,1,74,806,73,408,'','rack_psa',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (90,1,74,204,74,413,'','rack_server',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), (91,1,1424,806,73,408,'','rack_firewall',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), (92,1,1486,907,0,0,'<p style="text-align: center; overflow: hidden;"><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;"><strong><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;">Office 8 -&nbsp;</span></strong></span><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;">Rack 2</span></p>','white',4,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,0), (93,1,1048,889,58,281,'<p style="text-align: center; overflow: hidden;"><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;"><strong><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;">Office 8 -&nbsp;</span></strong></span><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;">Rack 1</span></p>','white',4,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,0), (94,1,580,904,0,0,'<p style="text-align: center; overflow: hidden;"><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;"><strong><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;">Office 7 -&nbsp;</span></strong></span><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;">Rack 2</span></p>','white',4,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,0), (95,1,132,907,0,0,'<p style="text-align: center; overflow: hidden;"><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;"><strong><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;">Office 7 -&nbsp;</span></strong></span><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;">Rack 1</span></p>','white',4,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,0), (96,1,733,20,0,0,'<p style="overflow: hidden;"><span class="visual_font_size_48pt"><strong><span style="color: #ffffff; font-family: opensans;">OFFICE RACKS</span></strong></span></p>','white',4,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,0), - (97,1,1479,260,174,29,'','rack_server_rack',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60) -; \ No newline at end of file + (97,1,1479,260,174,29,'','rack_server_rack',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,'0.000','0.000',0,0,'analogic_1','time','Europe/Madrid',0,60), + (98,2,709,103,0,400,'','white',19,3600,0,0,0,0,1,0,0,0,0,'line','down','','#FFFFFF',0,0,'default',0,0.000,0.000,0,0,'digital_1','timedate','Europe/Madrid',0,0), + (99,2,1251,382,0,0,'

    Disk /var

    \n

     

    ','white',4,3600,0,0,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0.000,0.000,0,0,'analogic_1','time','Europe/Madrid',0,0), + (100,2,1547,382,0,0,'<p style="line-height: 18px; overflow: hidden;"><span class="visual_font_size_28pt" style="color: #ffffff; font-family: opensans;">Authentification</span></p>','white',4,3600,0,0,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0.000,0.000,0,0,'analogic_1','time','Europe/Madrid',0,0), + (101,2,126,820,0,0,'<p style="line-height: 18px; overflow: hidden;"><strong><span class="visual_font_size_36pt" style="font-family: opensans; color: #ffffff;">Processing</span></strong></p>','white',4,3600,0,0,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0.000,0.000,0,0,'analogic_1','time','Europe/Madrid',0,0), + (102,2,755,820,0,0,'<p style="line-height: 18px; overflow: hidden;"><strong><span class="visual_font_size_36pt" style="font-family: opensans; color: #ffffff;">Network</span></strong></p>','white',4,3600,0,0,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0.000,0.000,0,0,'analogic_1','time','Europe/Madrid',0,0), + (103,2,1281,820,0,0,'<p style="line-height: 18px; overflow: hidden;"><strong><span class="visual_font_size_36pt" style="color: #ffffff; font-family: opensans;">Storage</span></strong></p>','white',4,3600,0,0,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0.000,0.000,0,0,'analogic_1','time','Europe/Madrid',0,0), + (104,2,157,393,0,0,'

    Backups

    \n

     

    ','white',4,3600,0,0,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0.000,0.000,0,0,'analogic_1','time','Europe/Madrid',0,0), + (105,2,512,382,96,172,'<p style="overflow: hidden;"><span class="visual_font_size_28pt" style="font-family: opensans; color: #ffffff;">DB Status</span></p> <p style="overflow: hidden;">&nbsp;</p>','white',4,3600,0,0,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0.000,0.000,0,0,'analogic_1','time','Europe/Madrid',0,0), + (106,2,886,382,0,0,'

    Disk slave

    \n

     

    ','white',4,3600,0,0,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0.000,0.000,0,0,'analogic_1','time','Europe/Madrid',0,0), + (107,2,178,481,111,111,'','status',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (108,2,542,481,111,111,'','status',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (109,2,905,481,111,111,'','status',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (110,2,1276,481,111,111,'','status',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (111,2,1631,482,111,111,'','status',0,3600,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0.000,0.000,0,0,'analogic_1','time','Europe/Madrid',0,0), + (112,2,387,825,100,226,'<p style="line-height: 26px;"><span class="visual_font_size_60pt"><strong><span style="line-height: 26px; font-family: roboto; color: #ffff99;">(_VALUE_)</span></strong></span></p>','',2,300,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (113,2,936,799,0,226,'<p style="line-height: 18px; overflow: hidden;"><strong><span class="visual_font_size_60pt" style="font-family: roboto; color: #ccffcc;">(_VALUE_)</span></strong></p>','',2,300,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0), + (114,2,1476,818,0,226,'<p style="line-height: 18px; overflow: hidden;"><span class="visual_font_size_36pt" style="color: #ccffff; font-family: roboto;">(_VALUE_)</span></p> <div id="gtx-trans" style="position: absolute; left: 43px; top: 4.65625px;">&nbsp;</div>','',2,300,1,1,0,0,1,0,0,0,0,'line','down','','',0,0,'default',0,0,0,0,0,'analogic_1','time','Europe/Madrid',0,0) +; diff --git a/pandora_console/vendor/mpdf/mpdf/ttfonts/smallfont.ttf b/pandora_console/vendor/mpdf/mpdf/ttfonts/smallfont.ttf new file mode 100644 index 0000000000..90c96f3129 Binary files /dev/null and b/pandora_console/vendor/mpdf/mpdf/ttfonts/smallfont.ttf differ diff --git a/pandora_console/vendor/mpdf/mpdf/ttfonts/unicode.ttf b/pandora_console/vendor/mpdf/mpdf/ttfonts/unicode.ttf new file mode 100755 index 0000000000..f077861ccd Binary files /dev/null and b/pandora_console/vendor/mpdf/mpdf/ttfonts/unicode.ttf differ diff --git a/pandora_server/DEBIAN/control b/pandora_server/DEBIAN/control index e699a5f1f1..69b27f4f9a 100644 --- a/pandora_server/DEBIAN/control +++ b/pandora_server/DEBIAN/control @@ -1,10 +1,10 @@ package: pandorafms-server -Version: 7.0NG.738-190913 +Version: 7.0NG.740-191029 Architecture: all Priority: optional Section: admin Installed-Size: 640 Maintainer: ÁRTICA ST Homepage: http://pandorafms.org/ -Depends: perl (>= 5.8), libdbi-perl, libdbd-mysql-perl, libtime-format-perl, libnetaddr-ip-perl, libtime-format-perl, libxml-simple-perl, libxml-twig-perl, libhtml-parser-perl, snmp, snmpd, traceroute, xprobe2, nmap, sudo, libwww-perl, libsocket6-perl, libio-socket-inet6-perl, snmp-mibs-downloader, libjson-perl, libnet-telnet-perl, libencode-locale-perl, libgeo-ip-perl +Depends: perl (>= 5.8), libdbi-perl, libdbd-mysql-perl, libtime-format-perl, libnetaddr-ip-perl, libtime-format-perl, libxml-simple-perl, libxml-twig-perl, libhtml-parser-perl, snmp, snmpd, traceroute, xprobe2, nmap, sudo, libwww-perl, libsocket6-perl, libio-socket-inet6-perl, libio-socket-ssl-perl, snmp-mibs-downloader, libjson-perl, libnet-telnet-perl, libencode-locale-perl, libgeo-ip-perl Description: Pandora FMS is a monitoring system for big IT environments. It uses remote tests, or local agents to grab information. Pandora supports all standard OS (Linux, AIX, HP-UX, Solaris and Windows XP,2000/2003), and support multiple setups in HA enviroments. This is the server package. Server makes the remote checks and process information transfer by Pandora FMS agents to the server. diff --git a/pandora_server/DEBIAN/make_deb_package.sh b/pandora_server/DEBIAN/make_deb_package.sh index e9a318fb60..34f150ed54 100644 --- a/pandora_server/DEBIAN/make_deb_package.sh +++ b/pandora_server/DEBIAN/make_deb_package.sh @@ -14,7 +14,7 @@ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. -pandora_version="7.0NG.738-190913" +pandora_version="7.0NG.740-191029" package_cpan=0 package_pandora=1 diff --git a/pandora_server/FreeBSD/pandora_server.conf.new b/pandora_server/FreeBSD/pandora_server.conf.new index 93d9abbc75..01ff859fa5 100644 --- a/pandora_server/FreeBSD/pandora_server.conf.new +++ b/pandora_server/FreeBSD/pandora_server.conf.new @@ -348,6 +348,15 @@ self_monitoring 1 # Self monitoring interval (in seconds). self_monitoring_interval 300 +# Pandora Sample Agent. If enabled, every 10 minutes, this embedded agent +# will make sample data. Disabled by default. + +sample_agent 0 + +# Pandora Sample Agent interval (in seconds). + +sample_agent_interval 600 + # Update parent from the agent xml #update_parent 1 diff --git a/pandora_server/NetBSD/pandora_server.conf.new b/pandora_server/NetBSD/pandora_server.conf.new index 5f38a678da..66743aee36 100644 --- a/pandora_server/NetBSD/pandora_server.conf.new +++ b/pandora_server/NetBSD/pandora_server.conf.new @@ -340,6 +340,15 @@ restart_delay 60 self_monitoring 1 +# Pandora Sample Agent. If enabled, every 10 minutes, this embedded agent +# will make sample data. Disabled by default. + +sample_agent 0 + +# Pandora Sample Agent interval (in seconds). + +sample_agent_interval 600 + # Update parent from the agent xml #update_parent 1 diff --git a/pandora_server/bin/pandora_server b/pandora_server/bin/pandora_server index bb177be783..1ce3e3da5e 100755 --- a/pandora_server/bin/pandora_server +++ b/pandora_server/bin/pandora_server @@ -97,9 +97,6 @@ sub pandora_startup () { # Grab config tokens shared with the console and not in the .conf pandora_get_sharedconfig (\%Config, $DBH); - - # Generate the encryption key after reading the passphrase. - $Config{"encryption_key"} = enterprise_hook('pandora_get_encryption_key', [\%Config, $Config{"encryption_passphrase"}]); # Kill any running server threads. stop_server_threads(); @@ -211,7 +208,9 @@ sub pandora_crash () { } $full_error .= $error_line; } - + + # Could crash before parse configuration. + $Config{'rb_product_name'} = 'PandoraFMS' unless defined($Config{'rb_product_name'}) && $Config{'rb_product_name'} ne ''; logger (\%Config, $Config{'rb_product_name'} . ' Server \'' . $Config{'servername'} . '\' unhandled error.', 1); # It's interesting show by console problems, not only in logs. This helps @@ -365,9 +364,11 @@ sub pandora_server_tasks ($) { # COMMON TASKS (master and non-master) # --------------------------------------------------------------- - - # Rotate Log File if (($counter % 30) == 0) { + # Update configuration options from the console. + pandora_get_sharedconfig ($pa_config, $dbh); + + # Rotate the log file. pandora_rotate_logfile($pa_config); # Set event storm protection @@ -381,6 +382,16 @@ sub pandora_server_tasks ($) { pandora_self_monitoring ($pa_config, $dbh); } + # Pandora sample agent + if (defined($pa_config->{'sample_agent'})) { + if ($pa_config->{'sample_agent'} == 1 + && !is_metaconsole($pa_config) + && $counter % $pa_config->{'sample_agent_interval'} == 0){ + pandora_sample_agent ($pa_config); + } + pandora_update_config_token ($dbh, 'sample_agent', $pa_config->{'sample_agent'}); + } + # Avoid counter overflow if ($counter >= ~0){ $counter = 0; diff --git a/pandora_server/conf/pandora_server.conf.new b/pandora_server/conf/pandora_server.conf.new index 33d34082c0..a5896e6050 100644 --- a/pandora_server/conf/pandora_server.conf.new +++ b/pandora_server/conf/pandora_server.conf.new @@ -1,7 +1,7 @@ ############################################################################# # Pandora FMS Server Parameters # Pandora FMS, the Flexible Monitoring System. -# Version 7.0NG.738 +# Version 7.0NG.740 # Licensed under GPL license v2, # (c) 2003-2017 Artica Soluciones Tecnologicas # http://www.pandorafms.com @@ -226,8 +226,9 @@ recon_threads 1 dataserver_threads 1 # mta_address: External Mailer (MTA) IP Address to be used by Pandora FMS internal email capabilities +# If not set, the MTA configuration specified in the Pandora FMS Console will be used. -mta_address localhost +#mta_address localhost # mta_port, this is the mail server port (default 25) @@ -250,6 +251,10 @@ mta_address localhost #mta_from Pandora FMS +# SMTP encryption protocol (none, ssl, starttls) + +#mta_encryption none + # Set 1 if want eMail deliver alert in separate mail (default). # Set 0 if want eMail deliver shared mail by all destination. mail_in_separate 1 @@ -371,6 +376,15 @@ self_monitoring 1 # Self monitoring interval (in seconds). self_monitoring_interval 300 +# Pandora Sample Agent. If enabled, every 10 minutes, this embedded agent +# will make sample data. Disabled by default. + +sample_agent 0 + +# Pandora Sample Agent interval (in seconds). + +sample_agent_interval 600 + # Update parent from the agent xml #update_parent 1 diff --git a/pandora_server/conf/pandora_server.conf.windows b/pandora_server/conf/pandora_server.conf.windows index a602f7abc4..a7232e459c 100644 --- a/pandora_server/conf/pandora_server.conf.windows +++ b/pandora_server/conf/pandora_server.conf.windows @@ -214,6 +214,7 @@ recon_threads 2 dataserver_threads 2 # mta_address: External Mailer (MTA) IP Address to be used by Pandora FMS internal email capabilities +# If not set, the MTA configuration specified in the Pandora FMS Console will be used. #mta_address localhost @@ -235,6 +236,10 @@ dataserver_threads 2 # probably you need to change it to avoid problems with your antispam #mta_from pandora@sampledomain.com +# SMTP encryption protocol (none, ssl, starttls) + +#mta_encryption none + # xprobe2: Optional package to detect OS types using advanced TCP/IP # fingerprinting tecniques, much more accurates than stadard nmap. # If not provided, nmap is used insted xprobe2 @@ -325,6 +330,15 @@ restart_delay 60 # Self monitoring interval (in seconds). #self_monitoring_interval 300 +# Pandora Sample Agent. If enabled, every 10 minutes, this embedded agent +# will make sample data. Disabled by default. + +sample_agent 0 + +# Pandora Sample Agent interval (in seconds). + +sample_agent_interval 600 + # Update parent from the agent xml #update_parent 1 diff --git a/pandora_server/lib/PandoraFMS/Config.pm b/pandora_server/lib/PandoraFMS/Config.pm index 84aec70255..1a7d0b44dd 100644 --- a/pandora_server/lib/PandoraFMS/Config.pm +++ b/pandora_server/lib/PandoraFMS/Config.pm @@ -44,8 +44,8 @@ our @EXPORT = qw( ); # version: Defines actual version of Pandora Server for this module only -my $pandora_version = "7.0NG.738"; -my $pandora_build = "190913"; +my $pandora_version = "7.0NG.740"; +my $pandora_build = "191029"; our $VERSION = $pandora_version." ".$pandora_build; # Setup hash @@ -79,7 +79,7 @@ sub help_screen { sub pandora_init { my $pa_config = $_[0]; my $init_string = $_[1]; - print "\n$init_string $pandora_version Build $pandora_build Copyright (c) 2004-2018 " . pandora_get_initial_copyright_notice() . "\n"; + print "\n$init_string $pandora_version Build $pandora_build Copyright (c) 2004-20".substr($pandora_build,0,2)." " . pandora_get_initial_copyright_notice() . "\n"; print "This program is OpenSource, licensed under the terms of GPL License version 2.\n"; print "You can download latest versions and documentation at official web page.\n\n"; @@ -187,6 +187,33 @@ sub pandora_get_sharedconfig ($$) { [$dbh] ); $pa_config->{'rb_product_name'} = 'Pandora FMS' unless (defined ($pa_config->{'rb_product_name'}) && $pa_config->{'rb_product_name'} ne ''); + + # Mail transport agent configuration. Local configuration takes precedence. + if ($pa_config->{"mta_local"} eq 0) { + $pa_config->{"mta_address"} = pandora_get_tconfig_token ($dbh, 'email_smtpServer', ''); + $pa_config->{"mta_from"} = '"' . pandora_get_tconfig_token ($dbh, 'email_from_name', 'Pandora FMS') . '" <' . + pandora_get_tconfig_token ($dbh, 'email_from_dir', 'pandora@pandorafms.org') . '>'; + $pa_config->{"mta_pass"} = pandora_get_tconfig_token ($dbh, 'email_password', ''); + $pa_config->{"mta_port"} = pandora_get_tconfig_token ($dbh, 'email_smtpPort', ''); + $pa_config->{"mta_user"} = pandora_get_tconfig_token ($dbh, 'email_username', ''); + $pa_config->{"mta_encryption"} = pandora_get_tconfig_token ($dbh, 'email_encryption', ''); + + # Auto-negotiate the auth mechanism, since it cannot be set from the console. + # Do not include PLAIN, it generates the following error: + # 451 4.5.0 SMTP protocol violation, see RFC 2821 + $pa_config->{"mta_auth"} = 'DIGEST-MD5 CRAM-MD5 LOGIN'; + + # Fix the format of mta_encryption. + if ($pa_config->{"mta_encryption"} eq 'tls') { + $pa_config->{"mta_encryption"} = 'starttls'; + } + elsif ($pa_config->{"mta_encryption"} =~ m/^ssl/) { + $pa_config->{"mta_encryption"} = 'ssl'; + } + else { + $pa_config->{"mta_encryption"} = 'none'; + } + } } ########################################################################## @@ -303,12 +330,14 @@ sub pandora_load_config { $pa_config->{"dynamic_constant"} = 10; # 7.0 # Internal MTA for alerts, each server need its own config. - $pa_config->{"mta_address"} = '127.0.0.1'; # Introduced on 2.0 - $pa_config->{"mta_port"} = '25'; # Introduced on 2.0 + $pa_config->{"mta_address"} = ''; # Introduced on 2.0 + $pa_config->{"mta_port"} = ''; # Introduced on 2.0 $pa_config->{"mta_user"} = ''; # Introduced on 2.0 $pa_config->{"mta_pass"} = ''; # Introduced on 2.0 $pa_config->{"mta_auth"} = 'none'; # Introduced on 2.0 (Support LOGIN PLAIN CRAM-MD5 DIGEST-MD) $pa_config->{"mta_from"} = 'pandora@localhost'; # Introduced on 2.0 + $pa_config->{"mta_encryption"} = 'none'; # 7.0 739 + $pa_config->{"mta_local"} = 0; # 7.0 739 $pa_config->{"mail_in_separate"} = 1; # 1: eMail deliver alert mail in separate mails. # 0: eMail deliver 1 mail with all destination. @@ -328,7 +357,15 @@ sub pandora_load_config { # Xprobe2 for recon OS fingerprinting and tcpscan (optional) $pa_config->{"xprobe2"} = "/usr/bin/xprobe2"; + # Winexe allows to exec commands on remote windows systems (optional) + $pa_config->{"winexe"} = "/usr/bin/winexe"; + + # PsExec allows to exec commands on remote windows systems from windows servers (optional) + $pa_config->{"psexec"} = 'C:\PandoraFMS\Pandora_Server\bin\PsExec.exe'; + # plink allows to exec commands on remote linux systems from windows servers (optional) + $pa_config->{"plink"} = 'C:\PandoraFMS\Pandora_Server\bin\plink.exe'; + # Snmpget for snmpget system command (optional) $pa_config->{"snmpget"} = "/usr/bin/snmpget"; @@ -360,6 +397,12 @@ sub pandora_load_config { # Self monitoring interval $pa_config->{'self_monitoring_interval'} = 300; # 5.1SP1 + # Sample Agent + $pa_config->{'sample_agent'} = 0; + + # Sample agent interval + $pa_config->{'sample_agent_interval'} = 600; + # Process XML data files as a stack $pa_config->{"dataserver_lifo"} = 0; # 5.0 @@ -582,6 +625,7 @@ sub pandora_load_config { } elsif ($parametro =~ m/^mta_address\s(.*)/i) { $pa_config->{'mta_address'}= clean_blank($1); + $pa_config->{'mta_local'}=1; } elsif ($parametro =~ m/^mta_port\s(.*)/i) { $pa_config->{'mta_port'}= clean_blank($1); @@ -592,6 +636,9 @@ sub pandora_load_config { elsif ($parametro =~ m/^mta_from\s(.*)/i) { $pa_config->{'mta_from'}= clean_blank($1); } + elsif ($parametro =~ m/^mta_encryption\s(.*)/i) { + $pa_config->{'mta_encryption'}= clean_blank($1); + } elsif ($parametro =~ m/^mail_in_separate\s+([0-9]*)/i) { $pa_config->{'mail_in_separate'}= clean_blank($1); } @@ -805,6 +852,15 @@ sub pandora_load_config { elsif ($parametro =~ m/^xprobe2\s(.*)/i) { $pa_config->{'xprobe2'}= clean_blank($1); } + elsif ($parametro =~ m/^winexe\s(.*)/i) { + $pa_config->{'winexe'}= clean_blank($1); + } + elsif ($parametro =~ m/^psexec\s(.*)/i) { + $pa_config->{'psexec'}= clean_blank($1); + } + elsif ($parametro =~ m/^plink\s(.*)/i) { + $pa_config->{'plink'}= clean_blank($1); + } elsif ($parametro =~ m/^snmpget\s(.*)/i) { $pa_config->{'snmpget'}= clean_blank($1); } @@ -896,6 +952,12 @@ sub pandora_load_config { elsif ($parametro =~ m/^self_monitoring_interval\s+([0-9]*)/i) { $pa_config->{'self_monitoring_interval'} = clean_blank($1); } + elsif ($parametro =~ m/^sample_agent\s+([0-1])/i) { + $pa_config->{'sample_agent'} = clean_blank($1); + } + elsif ($parametro =~ m/^sample_agent_interval\s+([0-9]*)/i) { + $pa_config->{'sample_agent_interval'} = clean_blank($1); + } elsif ($parametro =~ m/^update_parent\s+([0-1])/i) { $pa_config->{'update_parent'} = clean_blank($1); } @@ -1004,7 +1066,7 @@ sub pandora_load_config { $pa_config->{'console_pass'}= safe_input(clean_blank($1)); } elsif ($parametro =~ m/^encryption_passphrase\s(.*)/i) { # 6.0 - $pa_config->{'encryption_passphrase'}= safe_input(clean_blank($1)); + $pa_config->{'encryption_passphrase'} = clean_blank($1); } elsif ($parametro =~ m/^unknown_interval\s+([0-9]*)/i) { # > 5.1SP2 $pa_config->{'unknown_interval'}= clean_blank($1); @@ -1156,6 +1218,9 @@ sub pandora_load_config { } # end of loop for parameter # + # Generate the encryption key after reading the passphrase. + $pa_config->{"encryption_key"} = enterprise_hook('pandora_get_encryption_key', [$pa_config, $pa_config->{"encryption_passphrase"}]); + # Set to RDBMS' standard port if (!defined($pa_config->{'dbport'})) { if ($pa_config->{'dbengine'} eq "mysql") { diff --git a/pandora_server/lib/PandoraFMS/Core.pm b/pandora_server/lib/PandoraFMS/Core.pm index e1556d74b6..aaa2137cc4 100644 --- a/pandora_server/lib/PandoraFMS/Core.pm +++ b/pandora_server/lib/PandoraFMS/Core.pm @@ -100,6 +100,8 @@ Exported Functions: =item * C +=item * C + =back =head1 METHODS @@ -122,6 +124,7 @@ use threads::shared; use JSON qw(decode_json encode_json); use MIME::Base64; use Text::ParseWords; +use Math::Trig; # Math functions # Debugging #use Data::Dumper; @@ -247,6 +250,7 @@ our @EXPORT = qw( pandora_group_statistics pandora_server_statistics pandora_self_monitoring + pandora_sample_agent pandora_process_policy_queue subst_alert_macros subst_column_macros @@ -1137,23 +1141,25 @@ sub pandora_execute_action ($$$$$$$$$;$) { load_module_macros ($module->{'module_macros'}, \%macros); } - # User defined alerts + + #logger($pa_config, "Clean name ".$clean_name, 10); + # User defined alert if ($action->{'internal'} == 0) { - $macros{_field1_} = subst_alert_macros ($field1, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field2_} = subst_alert_macros ($field2, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field3_} = subst_alert_macros ($field3, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field4_} = subst_alert_macros ($field4, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field5_} = subst_alert_macros ($field5, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field6_} = subst_alert_macros ($field6, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field7_} = subst_alert_macros ($field7, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field8_} = subst_alert_macros ($field8, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field9_} = subst_alert_macros ($field9, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field10_} = subst_alert_macros ($field10, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field11_} = subst_alert_macros ($field11, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field12_} = subst_alert_macros ($field12, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field13_} = subst_alert_macros ($field13, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field14_} = subst_alert_macros ($field14, \%macros, $pa_config, $dbh, $agent, $module); - $macros{_field15_} = subst_alert_macros ($field15, \%macros, $pa_config, $dbh, $agent, $module); + $macros{_field1_} = subst_alert_macros ($field1, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field2_} = subst_alert_macros ($field2, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field3_} = subst_alert_macros ($field3, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field4_} = subst_alert_macros ($field4, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field5_} = subst_alert_macros ($field5, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field6_} = subst_alert_macros ($field6, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field7_} = subst_alert_macros ($field7, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field8_} = subst_alert_macros ($field8, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field9_} = subst_alert_macros ($field9, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field10_} = subst_alert_macros ($field10, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field11_} = subst_alert_macros ($field11, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field12_} = subst_alert_macros ($field12, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field13_} = subst_alert_macros ($field13, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field14_} = subst_alert_macros ($field14, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $macros{_field15_} = subst_alert_macros ($field15, \%macros, $pa_config, $dbh, $agent, $module, $alert); my @command_args = (); # divide command into words based on quotes and whitespaces @@ -1184,7 +1190,7 @@ sub pandora_execute_action ($$$$$$$$$;$) { # Internal Audit } elsif ($clean_name eq "Internal Audit") { - $field1 = subst_alert_macros ($field1, \%macros, $pa_config, $dbh, $agent, $module); + $field1 = subst_alert_macros ($field1, \%macros, $pa_config, $dbh, $agent, $module, $alert); pandora_audit ($pa_config, $field1, defined ($agent) ? safe_output($agent->{'alias'}) : 'N/A', 'Alert (' . safe_output($alert->{'description'}) . ')', $dbh); # Email @@ -1361,12 +1367,12 @@ sub pandora_execute_action ($$$$$$$$$;$) { # Pandora FMS Event } elsif ($clean_name eq "Monitoring Event") { - $field1 = subst_alert_macros ($field1, \%macros, $pa_config, $dbh, $agent, $module); - $field3 = subst_alert_macros ($field3, \%macros, $pa_config, $dbh, $agent, $module); - $field4 = subst_alert_macros ($field4, \%macros, $pa_config, $dbh, $agent, $module); - $field6 = subst_alert_macros ($field6, \%macros, $pa_config, $dbh, $agent, $module); - $field7 = subst_alert_macros ($field7, \%macros, $pa_config, $dbh, $agent, $module); - $field8 = subst_alert_macros ($field8, \%macros, $pa_config, $dbh, $agent, $module); + $field1 = subst_alert_macros ($field1, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $field3 = subst_alert_macros ($field3, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $field4 = subst_alert_macros ($field4, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $field6 = subst_alert_macros ($field6, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $field7 = subst_alert_macros ($field7, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $field8 = subst_alert_macros ($field8, \%macros, $pa_config, $dbh, $agent, $module, $alert); # Field 1 (event text) my $event_text = $field1; @@ -1442,62 +1448,76 @@ sub pandora_execute_action ($$$$$$$$$;$) { # Integria IMS Ticket } elsif ($clean_name eq "Integria IMS Ticket") { - $field1 = subst_alert_macros ($field1, \%macros, $pa_config, $dbh, $agent, $module); - $field3 = subst_alert_macros ($field3, \%macros, $pa_config, $dbh, $agent, $module); - $field5 = subst_alert_macros ($field5, \%macros, $pa_config, $dbh, $agent, $module); - $field7 = subst_alert_macros ($field7, \%macros, $pa_config, $dbh, $agent, $module); - $field8 = subst_alert_macros ($field8, \%macros, $pa_config, $dbh, $agent, $module); - $field9 = subst_alert_macros ($field9, \%macros, $pa_config, $dbh, $agent, $module); - $field10 = subst_alert_macros ($field10, \%macros, $pa_config, $dbh, $agent, $module); - + my $config_api_path = pandora_get_tconfig_token ($dbh, 'integria_hostname', ''); + my $config_api_pass = pandora_get_tconfig_token ($dbh, 'integria_api_pass', ''); + my $config_integria_user = pandora_get_tconfig_token ($dbh, 'integria_user', ''); + my $config_integria_user_pass = pandora_get_tconfig_token ($dbh, 'integria_pass', ''); + $field1 = subst_alert_macros ($field1, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $field2 = subst_alert_macros ($field2, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $field3 = subst_alert_macros ($field3, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $field4 = subst_alert_macros ($field4, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $field5 = subst_alert_macros ($field5, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $field6 = subst_alert_macros ($field6, \%macros, $pa_config, $dbh, $agent, $module, $alert); + $field7 = subst_alert_macros ($field7, \%macros, $pa_config, $dbh, $agent, $module, $alert); + # Field 1 (Integria IMS API path) - my $api_path = $field1; + my $api_path = $config_api_path . "/integria/include/api.php"; # Field 2 (Integria IMS API pass) - my $api_pass = $field2; + my $api_pass = $config_api_pass; # Field 3 (Integria IMS user) - my $integria_user = $field3; + my $integria_user = $config_integria_user; # Field 4 (Integria IMS user password) - my $integria_user_pass = $field4; + my $integria_user_pass = $config_integria_user_pass; - # Field 5 (Ticket name) - my $ticket_name = $field5; + # Field 1 (Ticket name) + my $ticket_name = safe_output($field1); if ($ticket_name eq "") { $ticket_name = $pa_config->{'rb_product_name'} . " alert action created by API"; } - # Field 6 (Ticket group ID) - my $ticket_group_id = $field6; + # Field 2 (Ticket group ID) + my $ticket_group_id = $field2; if ($ticket_group_id eq '') { $ticket_group_id = 0; } - # Field 7 (Ticket priority); - my $ticket_priority = $field7; - if ($ticket_priority eq '') { - $ticket_priority = 0; + # Field 3 (Ticket priority); + my $ticket_priority = $field3; + if ($ticket_priority eq '0') { + $ticket_priority = 1; + } + + # Field 4 (Ticket owner) + my $ticket_owner = $field4; + if ($ticket_owner eq '') { + $ticket_owner = 'admin'; } - # Field 8 (Ticket email) - my $ticket_email = $field8; - - # Field 9 (Ticket owner) - my $ticket_owner = $field9; - - # Field 10 (Ticket description); - my $ticket_description = $field10; + # Field 5 (Ticket type) + my $ticket_type = $field5; + if ($ticket_type eq '') { + $ticket_type = 0; + } - pandora_create_integria_ticket($pa_config, $api_path, $api_pass, $integria_user, $integria_user_pass, $ticket_name, $ticket_group_id, $ticket_priority, $ticket_email, $ticket_owner, $ticket_description); + # Field 6 (Ticket status) + my $ticket_status = $field6; + if ($ticket_status eq '0') { + $ticket_status = 1; + } + # Field 7 (Ticket description); + my $ticket_description = safe_output($field7); + + pandora_create_integria_ticket($pa_config, $api_path, $api_pass, $integria_user, $integria_user_pass, $ticket_name, $ticket_group_id, $ticket_priority, $ticket_owner, $ticket_type, $ticket_status, $ticket_description); # Generate notification } elsif ($clean_name eq "Generate Notification") { # Translate macros - $field3 = subst_alert_macros($field3, \%macros, $pa_config, $dbh, $agent, $module); - $field4 = subst_alert_macros($field4, \%macros, $pa_config, $dbh, $agent, $module); + $field3 = subst_alert_macros($field3, \%macros, $pa_config, $dbh, $agent, $module, $alert); # If no targets ignore notification if (defined($field1) && defined($field2) && ($field1 ne "" || $field2 ne "")) { @@ -3155,11 +3175,20 @@ sub pandora_get_config_value ($$) { ########################################################################## ## Get credential from credential store ########################################################################## -sub pandora_get_credential ($$) { - my ($dbh, $identifier) = @_; +sub pandora_get_credential ($$$) { + my ($pa_config, $dbh, $identifier) = @_; my $key = get_db_single_row($dbh, 'SELECT * FROM tcredential_store WHERE identifier = ?', $identifier); + $key->{'username'} = pandora_output_password( + $pa_config, + safe_output($key->{'username'}) + ); + $key->{'password'} = pandora_output_password( + $pa_config, + safe_output($key->{'password'}) + ); + return $key; } @@ -3233,7 +3262,7 @@ sub pandora_create_agent ($$$$$$$$$$;$$$$$$$$$$) { 'custom_id' => $custom_id, 'url_address' => $url_address, 'timezone_offset' => $timezone_offset, - 'alias' => $alias, + 'alias' => safe_input($alias), 'update_module_count' => 1, # Force to replicate in metaconsole }); @@ -4068,7 +4097,7 @@ sub on_demand_macro($$$$$$;$) { my $unit_mod = get_db_value ($dbh, 'SELECT unit FROM tagente_modulo WHERE id_agente_modulo = ?', $id_mod); my $field_value = ""; - if ($type_mod eq 3){ + if ($type_mod eq 3 || $type_mod eq 23|| $type_mod eq 17 || $type_mod eq 10 || $type_mod eq 33 ){ $field_value = get_db_value($dbh, 'SELECT datos FROM tagente_datos_string where id_agente_modulo = ? order by utimestamp desc limit 1', $id_mod); } else{ @@ -5210,6 +5239,83 @@ sub pandora_self_monitoring ($$) { print XMLFILE $xml_output; close (XMLFILE); } +########################################################################## +=head2 C<< xml_module_template (I<$module_name>, I<$module_type>, I<$module_data>) >> + +Module template for sample agent + +=cut +########################################################################## +sub xml_module_template ($$$) { + my ($module_name, $module_type, $module_data) = @_; + my $output = "\n"; + + $module_name = "" if $module_name =~ /[\s+.]+/; + $module_data = "" if $module_data =~ /[\s+.]+/; + + $output .= "\t".$module_name."\n"; + $output .= "\t".$module_type."\n"; + $output .= "\t".$module_data."\n"; + $output .= "\n"; + + return $output; +} +########################################################################## +=head2 C<< pandora_sample_agent (I<$pa_config>) >> + +Pandora agent for make sample data + +=cut +########################################################################## +sub pandora_sample_agent ($) { + + my ($pa_config) = @_; + + my $utimestamp = time (); + my $timestamp = strftime ("%Y-%m-%d %H:%M:%S", localtime()); + # First line + my $xml_output = "\n"; + # Header + $xml_output = "\n"; + # Boolean ever return TRUE + $xml_output .= xml_module_template ("Boolean ever true", "generic_proc","1"); + # Boolean return TRUE at 80% of times + my $sample_boolean_mostly_true = 1; + $sample_boolean_mostly_true = 0 if rand(9) > 7; + $xml_output .= xml_module_template ("Boolean mostly true", "generic_proc",$sample_boolean_mostly_true); + # Boolean return false at 80% of times + my $sample_boolean_mostly_false = 0; + $sample_boolean_mostly_false = 1 if rand(9) > 7; + $xml_output .= xml_module_template ("Boolean mostly false", "generic_proc", $sample_boolean_mostly_false); + # Boolean ever return FALSE + $xml_output .= xml_module_template ("Boolean ever false", "generic_proc","0"); + # Random integer between 0 and 100 + $xml_output .= xml_module_template ("Random integer values", "generic_data",int(rand(100))); + # Random values obtained with sinusoidal curves between 0 and 100 values + my $b = 1; + my $sample_serie_curve = 1 + cos(deg2rad($b)); + $b = $b + rand(20)/10; + $b = 0 if ($b > 180); + $sample_serie_curve = $sample_serie_curve * $b * 10; + $sample_serie_curve =~ s/\,/\./g; + $xml_output .= xml_module_template ("Random serie curve", "generic_data", $sample_serie_curve); + # String with 10 random characters + my $sample_random_text = ""; + my @characters = ('a'..'z','A'..'Z'); + for (1...10){ + $sample_random_text .= $characters[int(rand(@characters))]; + } + $xml_output .= xml_module_template ("Random text", "generic_data_string", $sample_random_text); + # End of xml + $xml_output .= ""; + # File path definition + my $filename = $pa_config->{"incomingdir"}."/".$pa_config->{'servername'}.".sample.".$utimestamp.".data"; + # Opening, Writing and closing of XML + open (my $xmlfile, ">", $filename) or die "[FATAL] Could not open sample XML file for deploying monitorization at '$filename'"; + print $xmlfile $xml_output; + close ($xmlfile); + +} ########################################################################## =head2 C<< set_master (I<$pa_config>, I<$dbh>) >> @@ -5840,55 +5946,21 @@ sub pandora_edit_custom_graph ($$$$$$$$$$$) { } sub pandora_create_integria_ticket ($$$$$$$$$$$) { - my ($pa_config,$api_path,$api_pass,$integria_user,$user_pass,$ticket_name,$group_id,$ticket_priority,$ticket_email,$ticket_owner,$ticket_description) = @_; - + my ($pa_config,$api_path,$api_pass,$integria_user,$user_pass,$ticket_name,$ticket_group_id,$ticket_priority,$ticket_owner,$ticket_type,$ticket_status,$ticket_description) = @_; + my $data_ticket; my $call_api; - if ($api_path eq "") { - return 0; - } - if ($user_pass eq "") { - return 0; - } - if ($integria_user eq "") { - $integria_user = "admin"; - } - if ($ticket_name eq "") { - $ticket_name = "Ticket created by " . $pa_config->{'rb_product_name'}; - } - if ($group_id eq "") { - $group_id = 1; - } - if ($ticket_priority eq "") { - $ticket_priority = 1; - } - if ($ticket_owner eq "") { - $ticket_owner = "admin"; - } - - #~ $data_ticket = $ticket_name . - #~ "|;|" . $group_id . - #~ "|;|" . $ticket_priority . - #~ "|;|" . $ticket_description . - #~ "|;|" . #Id inventory - #~ "|;|" . #Id incident type - #~ "|;|" . $ticket_email . - #~ "|;|" . $ticket_owner . - #~ "|;|" . #Father ticket id - #~ "|;|" . #Status - #~ "|;|" . #Extra info - #~ "|;|"; #Resolution $data_ticket = $ticket_name . - "|;|" . $group_id . + "|;|" . $ticket_group_id . "|;|" . $ticket_priority . "|;|" . $ticket_description . "|;|" . - "|;|" . - "|;|" . $ticket_email . + "|;|" . $ticket_type . + "|;|" . "|;|" . $ticket_owner . "|;|" . - "|;|" . '1' . + "|;|" . $ticket_status . "|;|" . "|;|"; @@ -5899,9 +5971,9 @@ sub pandora_create_integria_ticket ($$$$$$$$$$$) { 'op=create_incident&' . 'params=' . $data_ticket .'&' . 'token=|;|'; - logger($pa_config, "Integria ticket call:" . $call_api . "", 3); + my $content = get($call_api); - logger($pa_config, "Integria ticket res:" . $content . "", 3); + if (is_numeric($content) && $content ne "-1") { return $content; } diff --git a/pandora_server/lib/PandoraFMS/DB.pm b/pandora_server/lib/PandoraFMS/DB.pm index a257d5df07..63c756e5ae 100644 --- a/pandora_server/lib/PandoraFMS/DB.pm +++ b/pandora_server/lib/PandoraFMS/DB.pm @@ -57,6 +57,7 @@ our @EXPORT = qw( get_addr_id get_agent_addr_id get_agent_id + get_agent_ids_from_alias get_agent_address get_agent_alias get_agent_group @@ -232,6 +233,17 @@ sub get_agent_id ($$) { return defined ($rc) ? $rc : -1; } +######################################################################## +## Return agent IDs given an agent alias. +######################################################################## +sub get_agent_ids_from_alias ($$) { + my ($dbh, $agent_alias) = @_; + + my @rc = get_db_rows ($dbh, "SELECT id_agente, nombre FROM tagente WHERE alias = ?", safe_input($agent_alias)); + + return @rc; +} + ######################################################################## ## Return server ID given the name of server. ######################################################################## @@ -956,7 +968,7 @@ sub db_process_insert($$$$;@) { } } my $columns_string = join(',', @columns_array); - + my $res = db_insert ($dbh, $index, "INSERT INTO $table ($columns_string) VALUES " . $wildcards, @values_array); diff --git a/pandora_server/lib/PandoraFMS/DataServer.pm b/pandora_server/lib/PandoraFMS/DataServer.pm index b7beb919a3..df1cbbecfb 100644 --- a/pandora_server/lib/PandoraFMS/DataServer.pm +++ b/pandora_server/lib/PandoraFMS/DataServer.pm @@ -230,7 +230,7 @@ sub data_consumer ($$) { } # Ignore the timestamp in the XML and use the file timestamp instead - $xml_data->{'timestamp'} = strftime ("%Y-%m-%d %H:%M:%S", localtime((stat($file_name))[9])) if ($pa_config->{'use_xml_timestamp'} eq '1' || ! defined ($xml_data->{'timestamp'})); + $xml_data->{'timestamp'} = strftime ("%Y-%m-%d %H:%M:%S", localtime((stat($file_name))[9])) if ($pa_config->{'use_xml_timestamp'} eq '0' || ! defined ($xml_data->{'timestamp'})); # Double check that the file exists if (! -f $file_name) { diff --git a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm index 6f7eab4c68..7d90ff411a 100644 --- a/pandora_server/lib/PandoraFMS/DiscoveryServer.pm +++ b/pandora_server/lib/PandoraFMS/DiscoveryServer.pm @@ -343,6 +343,9 @@ sub exec_recon_script ($$$) { sub PandoraFMS::Recon::Base::guess_os($$) { my ($self, $device) = @_; + $DEVNULL = '/dev/null' if (!defined($DEVNULL)); + $DEVNULL = '/NUL' if ($^O =~ /win/i && !defined($DEVNULL)); + # OS detection disabled. Use the device type. if ($self->{'os_detection'} == 0) { my $device_type = $self->get_device_type($device); @@ -354,18 +357,23 @@ sub PandoraFMS::Recon::Base::guess_os($$) { } # Use xprobe2 if available - if (-e $self->{pa_config}->{xprobe2}) { - my $output = `"$self->{pa_config}->{xprobe2}" $device 2>$DEVNULL | grep 'Running OS' | head -1`; + if (-x $self->{'pa_config'}->{'xprobe2'}) { + my $return = `"$self->{pa_config}->{xprobe2}" $device 2>$DEVNULL`; if ($? == 0) { - return pandora_get_os($self->{'dbh'}, $output); + if($return =~ /Running OS:(.*)/) { + return pandora_get_os($self->{'dbh'}, $1); + } } } # Use nmap by default - if (-e $self->{pa_config}->{nmap}) { - my $output = `"$self->{pa_config}->{nmap}" -F -O $device 2>$DEVNULL | grep 'Aggressive OS guesses'`; + if (-x $self->{'pa_config'}->{'nmap'}) { + my $return = `"$self->{pa_config}->{nmap}" -F -O $device 2>$DEVNULL`; return OS_OTHER if ($? != 0); - return pandora_get_os($self->{'dbh'}, $output); + + if ($return =~ /Aggressive OS guesses:\s*(.*)/) { + return pandora_get_os($self->{'dbh'}, $1); + } } return OS_OTHER; @@ -377,7 +385,11 @@ sub PandoraFMS::Recon::Base::guess_os($$) { sub PandoraFMS::Recon::Base::tcp_scan ($$) { my ($self, $host) = @_; - my $open_ports = `"$self->{pa_config}->{nmap}" -p$self->{recon_ports} $host | grep open | wc -l`; + my $r = `"$self->{pa_config}->{nmap}" -p$self->{recon_ports} $host`; + + # Same as ""| grep open | wc -l" but multi-OS; + my $open_ports = () = $r =~ /open/gm; + return $open_ports; } @@ -526,7 +538,7 @@ sub PandoraFMS::Recon::Base::create_agents($$) { return undef; } - if ($agent->{'address'} ne '') { + if (defined($agent->{'address'}) && $agent->{'address'} ne '') { pandora_add_agent_address( $pa_config, $agent_id, $agent->{'agent_name'}, $agent->{'address'}, $dbh @@ -572,44 +584,14 @@ sub PandoraFMS::Recon::Base::create_agent($$) { # Clean name. $device = clean_blank($device); - my @agents = get_db_rows($self->{'dbh'}, - 'SELECT * FROM taddress, taddress_agent, tagente - WHERE tagente.id_agente = taddress_agent.id_agent - AND taddress_agent.id_a = taddress.id_a - AND ip = ?', $device - ); - - # Does the host already exist? - my $agent; - foreach my $candidate (@agents) { - $agent = {map {$_} %$candidate}; # copy contents, do not use shallow copy - # exclude $device itself, because it handle corner case when target includes NAT - my @registered = map {$_->{ip}} get_db_rows($self->{'dbh'}, - 'SELECT ip FROM taddress, taddress_agent, tagente - WHERE tagente.id_agente = taddress_agent.id_agent - AND taddress_agent.id_a = taddress.id_a - AND tagente.id_agente = ? - AND taddress.ip != ?', $agent->{id_agente}, $device - ); - foreach my $ip_addr (@registered) { - my @matched = grep { $_ =~ /^$ip_addr$/ } $self->get_addresses($device); - if (scalar(@matched) == 0) { - $agent = undef; - last; - } - } - last if(defined($agent)); # exit loop if match all ip_addr - } - - if (!defined($agent)) { - $agent = get_agent_from_name($self->{'dbh'}, $device); - } + # Resolve hostnames. + my $host_name = (($self->{'resolve_names'} == 1) ? gethostbyaddr(inet_aton($device), AF_INET) : $device); + # Fallback to device IP if host name could not be resolved. + $host_name = $device if (!defined($host_name) || $host_name eq ''); + my $agent = locate_agent($self->{'pa_config'}, $self->{'dbh'}, $host_name); my ($agent_id, $agent_learning); if (!defined($agent)) { - - # Resolve hostnames. - my $host_name = $self->{'resolve_names'} == 1 ? gethostbyaddr (inet_aton($device), AF_INET) : $device; $host_name = $device unless defined ($host_name); # Guess the OS. diff --git a/pandora_server/lib/PandoraFMS/PluginTools.pm b/pandora_server/lib/PandoraFMS/PluginTools.pm index d0673b4223..287b11e900 100644 --- a/pandora_server/lib/PandoraFMS/PluginTools.pm +++ b/pandora_server/lib/PandoraFMS/PluginTools.pm @@ -31,8 +31,8 @@ use base 'Exporter'; our @ISA = qw(Exporter); # version: Defines actual version of Pandora Server for this module only -my $pandora_version = "7.0NG.738"; -my $pandora_build = "190913"; +my $pandora_version = "7.0NG.740"; +my $pandora_build = "191029"; our $VERSION = $pandora_version." ".$pandora_build; our %EXPORT_TAGS = ( 'all' => [ qw() ] ); @@ -762,7 +762,7 @@ sub transfer_xml { my $file_path; if (! (empty ($name))) { - $file_name = $name . "." . sprintf("%d",time()) . ".data"; + $file_name = $name . "." . sprintf("%d",getCurrentUTimeMilis(). (rand()*10000)) . ".data"; } else { # Inherit file name diff --git a/pandora_server/lib/PandoraFMS/Recon/Base.pm b/pandora_server/lib/PandoraFMS/Recon/Base.pm index 223c36f248..335504821e 100644 --- a/pandora_server/lib/PandoraFMS/Recon/Base.pm +++ b/pandora_server/lib/PandoraFMS/Recon/Base.pm @@ -36,7 +36,7 @@ use constant { DISCOVERY_DEPLOY_AGENTS => 9, }; -# /dev/null +# $DEVNULL my $DEVNULL = ($^O eq 'MSWin32') ? '/Nul' : '/dev/null'; # Some useful OIDs. @@ -852,7 +852,7 @@ sub get_routes($) { $self->{'routes'} = []; # Parse route's output. - my @output = `route -n 2>/dev/null`; + my @output = `route -n 2>$DEVNULL`; foreach my $line (@output) { chomp($line); if ($line =~ /^0\.0\.0\.0\s+(\d+\.\d+\.\d+\.\d+).*/) { @@ -1220,7 +1220,7 @@ sub snmp_responds_v3($$) { sub local_arp($) { my ($self) = @_; - my @output = `arp -an 2>/dev/null`; + my @output = `arp -an 2>$DEVNULL`; foreach my $line (@output) { next unless ($line =~ m/\((\S+)\) at ([0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+)/); $self->add_mac(parse_mac($2), $1); @@ -1286,7 +1286,7 @@ sub ping ($$$) { for (my $i = 0; $i < $retries; $i++) { # Note: There is no timeout option. - `$ping_command -s -n $host 56 $packets >/dev/null 2>&1`; + `$ping_command -s -n $host 56 $packets >$DEVNULL 2>&1`; return 1 if ($? == 0); } @@ -1299,7 +1299,7 @@ sub ping ($$$) { for (my $i = 0; $i < $retries; $i++) { # Note: There is no timeout option for ping6. - `$ping_command -q -n -c $packets $host >/dev/null 2>&1`; + `$ping_command -q -n -c $packets $host >$DEVNULL 2>&1`; return 1 if ($? == 0); } @@ -1312,7 +1312,7 @@ sub ping ($$$) { for (my $i = 0; $i < $retries; $i++) { # Note: There is no timeout option for ping6. - `$ping_command -q -n -c $packets $host >/dev/null 2>&1`; + `$ping_command -q -n -c $packets $host >$DEVNULL 2>&1`; if ($? == 0) { return 1; } @@ -1324,7 +1324,7 @@ sub ping ($$$) { # Assume Linux by default. my $ping_command = $host =~ /\d+:|:\d+/ ? "ping6" : "ping"; for (my $i = 0; $i < $retries; $i++) { - `$ping_command -q -W $timeout -n -c $packets $host >/dev/null 2>&1`; + `$ping_command -q -W $timeout -n -c $packets $host >$DEVNULL 2>&1`; return 1 if ($? == 0); } @@ -1529,99 +1529,101 @@ sub app_scan($) { $self->{'task_data'} ); - if (!$dbObj->is_connected()) { - call('message', 'Cannot connect to target ' . $target, 3); - $global_percent += $global_step; - $self->{'c_network_percent'} = 90; - # Update progress - $self->call('update_progress', $global_percent + (90 / (scalar @targets))); - $self->{'summary'}->{'not_alive'} += 1; - push @modules, { - name => $type . ' connection', - type => 'generic_proc', - data => 0, - description => $type . ' availability' - }; + if (defined($dbObj)) { + if (!$dbObj->is_connected()) { + call('message', 'Cannot connect to target ' . $target, 3); + $global_percent += $global_step; + $self->{'c_network_percent'} = 90; + # Update progress + $self->call('update_progress', $global_percent + (90 / (scalar @targets))); + $self->{'summary'}->{'not_alive'} += 1; + push @modules, { + name => $type . ' connection', + type => 'generic_proc', + data => 0, + description => $type . ' availability' + }; - } else { - my $dbObjCfg = $dbObj->get_config(); + } else { + my $dbObjCfg = $dbObj->get_config(); - $self->{'summary'}->{'discovered'} += 1; - $self->{'summary'}->{'alive'} += 1; + $self->{'summary'}->{'discovered'} += 1; + $self->{'summary'}->{'alive'} += 1; - push @modules, { - name => $type . ' connection', - type => 'generic_proc', - data => 1, - description => $type . ' availability' - }; + push @modules, { + name => $type . ' connection', + type => 'generic_proc', + data => 1, + description => $type . ' availability' + }; - # Analyze. - $self->{'step'} = STEP_STATISTICS; - $self->{'c_network_percent'} = 30; - $self->call('update_progress', $global_percent + (30 / (scalar @targets))); - $self->{'c_network_name'} = $dbObj->get_host(); + # Analyze. + $self->{'step'} = STEP_STATISTICS; + $self->{'c_network_percent'} = 30; + $self->call('update_progress', $global_percent + (30 / (scalar @targets))); + $self->{'c_network_name'} = $dbObj->get_host(); - # Retrieve connection statistics. - # Retrieve uptime statistics - # Retrieve query stats - # Retrieve connections - # Retrieve innodb - # Retrieve cache - $self->{'c_network_percent'} = 50; - $self->call('update_progress', $global_percent + (50 / (scalar @targets))); - push @modules, $dbObj->get_statistics(); + # Retrieve connection statistics. + # Retrieve uptime statistics + # Retrieve query stats + # Retrieve connections + # Retrieve innodb + # Retrieve cache + $self->{'c_network_percent'} = 50; + $self->call('update_progress', $global_percent + (50 / (scalar @targets))); + push @modules, $dbObj->get_statistics(); - # Custom queries. - $self->{'step'} = STEP_CUSTOM_QUERIES; - $self->{'c_network_percent'} = 80; - $self->call('update_progress', $global_percent + (80 / (scalar @targets))); - push @modules, $dbObj->execute_custom_queries(); + # Custom queries. + $self->{'step'} = STEP_CUSTOM_QUERIES; + $self->{'c_network_percent'} = 80; + $self->call('update_progress', $global_percent + (80 / (scalar @targets))); + push @modules, $dbObj->execute_custom_queries(); - if (defined($dbObjCfg->{'scan_databases'}) - && $dbObjCfg->{'scan_databases'} == 1) { - # Skip database scan in Oracle tasks - next if $self->{'type'} == DISCOVERY_APP_ORACLE; + if (defined($dbObjCfg->{'scan_databases'}) + && "$dbObjCfg->{'scan_databases'}" eq "1") { + # Skip database scan in Oracle tasks + next if $self->{'type'} == DISCOVERY_APP_ORACLE; - my $__data = $dbObj->scan_databases(); + my $__data = $dbObj->scan_databases(); - if (ref($__data) eq "ARRAY") { - if (defined($dbObjCfg->{'agent_per_database'}) - && $dbObjCfg->{'agent_per_database'} == 1) { - # Agent per database detected. - push @data, @{$__data}; - } else { - # Merge modules into engine agent. - my @_modules = map { - map { $_ } @{$_->{'module_data'}} - } @{$__data}; + if (ref($__data) eq "ARRAY") { + if (defined($dbObjCfg->{'agent_per_database'}) + && $dbObjCfg->{'agent_per_database'} == 1) { + # Agent per database detected. + push @data, @{$__data}; + } else { + # Merge modules into engine agent. + my @_modules = map { + map { $_ } @{$_->{'module_data'}} + } @{$__data}; - push @modules, @_modules; + push @modules, @_modules; + } } } } + + # Put engine agent at the beginning of the list. + my $version = $dbObj->get_version(); + unshift @data,{ + 'agent_data' => { + 'agent_name' => $dbObj->get_agent_name(), + 'os' => $type, + 'os_version' => (defined($version) ? $version : 'Discovery'), + 'interval' => $self->{'task_data'}->{'interval_sweep'}, + 'id_group' => $self->{'task_data'}->{'id_group'}, + 'address' => $dbObj->get_host(), + 'description' => '', + }, + 'module_data' => \@modules, + }; + + $self->call('create_agents', \@data); + + # Destroy item. + undef($dbObj); } - # Put engine agent at the beginning of the list. - my $version = $dbObj->get_version(); - unshift @data,{ - 'agent_data' => { - 'agent_name' => $dbObj->get_agent_name(), - 'os' => $type, - 'os_version' => (defined($version) ? $version : 'Discovery'), - 'interval' => $self->{'task_data'}->{'interval_sweep'}, - 'id_group' => $self->{'task_data'}->{'id_group'}, - 'address' => $dbObj->get_host(), - 'description' => '', - }, - 'module_data' => \@modules, - }; - - $self->call('create_agents', \@data); - - # Destroy item. - undef($dbObj); - $global_percent += $global_step; $self->{'c_network_percent'} = 100; $self->call('update_progress', $global_percent); @@ -1674,7 +1676,7 @@ sub deploy_scan($) { ########################################################################## sub scan($) { my ($self) = @_; - my ($progress, $step); + my ($progress, $step) = 1, 0; # 1% $self->call('update_progress', 1); @@ -1697,7 +1699,7 @@ sub scan($) { } # Find devices. - $self->call('message', "[1/5] Scanning the network...", 3); + $self->call('message', "[1/4] Scanning the network...", 3); $self->{'step'} = STEP_SCANNING; $self->call('update_progress', $progress); $self->scan_subnet(); @@ -1713,7 +1715,7 @@ sub scan($) { $self->call('delete_connections'); # Connectivity from address forwarding tables. - $self->call('message', "[1/4] Finding address forwarding table connectivity...", 3); + $self->call('message', "[2/4] Finding address forwarding table connectivity...", 3); $self->{'step'} = STEP_AFT; ($progress, $step) = (50, 20.0 / scalar(@hosts)); # From 50% to 70%. for (my $i = 0; defined($hosts[$i]); $i++) { @@ -1831,7 +1833,7 @@ sub snmp_get_command { my ($self, $device, $oid, $community, $vlan) = @_; $vlan = defined($vlan) ? "\@" . $vlan : ''; - my $command = "snmpwalk -M/dev/null -r$self->{'snmp_checks'} -t$self->{'snmp_timeout'} -v$self->{'snmp_version'} -On -Oe "; + my $command = "snmpwalk -M$DEVNULL -r$self->{'snmp_checks'} -t$self->{'snmp_timeout'} -v$self->{'snmp_version'} -On -Oe "; if ($self->{'snmp_version'} eq "3") { if ($self->{'community'}) { # Context $command .= " -N $self->{'community'} "; @@ -1847,7 +1849,7 @@ sub snmp_get_command { $command .= " -c$community$vlan "; } - return "$command $device $oid 2>/dev/null"; + return "$command $device $oid 2>$DEVNULL"; } diff --git a/pandora_server/lib/PandoraFMS/Sendmail.pm b/pandora_server/lib/PandoraFMS/Sendmail.pm index 394add6d1f..08819c78ab 100644 --- a/pandora_server/lib/PandoraFMS/Sendmail.pm +++ b/pandora_server/lib/PandoraFMS/Sendmail.pm @@ -32,7 +32,9 @@ $VERSION = '0.79_16'; 'tz' => '', # only to override automatic detection 'port' => 25, # change it if you always use a non-standard port - 'debug' => 0 # prints stuff to STDERR + 'debug' => 0, # prints stuff to STDERR + 'encryption' => 'none', # no, ssl or starttls + 'timeout' => 5, # timeout for socket reads/writes in seconds ); # ******************************************************************* @@ -54,7 +56,8 @@ use vars qw( $auth_support ); -use Socket; +use IO::Socket::INET; +use IO::Select; use Time::Local; # for automatic time zone detection use Sys::Hostname; # for use of hostname in HELO @@ -62,6 +65,12 @@ use Sys::Hostname; # for use of hostname in HELO $auth_support = 'DIGEST-MD5 CRAM-MD5 PLAIN LOGIN'; +# IO::Socket object. +my $S; + +# IO::Select object. +my $Sel; + # use MIME::QuotedPrint if available and configured in %mailcfg eval("use MIME::QuotedPrint"); $mailcfg{'mime'} &&= (!$@); @@ -178,9 +187,9 @@ sub sendmail { local $_; my (%mail, $k, - $smtp, $server, $port, $connected, $localhost, + $smtp, $server, $port, $localhost, $fromaddr, $recip, @recipients, $to, $header, - %esmtp, @wanted_methods, + %esmtp, @wanted_methods, $encryption ); use vars qw($server_reply); # -------- a few internal subs ---------- @@ -191,7 +200,7 @@ sub sendmail { $error .= "Server said: $server_reply\n"; print STDERR "Server said: $server_reply\n" if $^W; } - close S; + close $S if defined($S); return 0; } @@ -200,31 +209,40 @@ sub sendmail { for $i (0..$#_) { # accept references, so we don't copy potentially big data my $data = ref($_[$i]) ? $_[$i] : \$_[$i]; - if ($mailcfg{'debug'} > 5) { + if ($mailcfg{'debug'} > 9) { if (length($$data) < 500) { - print ">", $$data; + print STDERR ">", $$data; } else { - print "> [...", length($$data), " bytes sent ...]\n"; + print STDERR "> [...", length($$data), " bytes sent ...]\n"; } } - print(S $$data) || return 0; + my @sockets = $Sel->can_write($mailcfg{'timeout'}); + return 0 if (!@sockets); + syswrite($sockets[0], $$data) || return 0; } 1; } sub socket_read { + my $buffer; $server_reply = ""; - do { - $_ = ; - $server_reply .= $_; - #chomp $_; - print "<$_" if $mailcfg{'debug'} > 5; - if (/^[45]/ or !$_) { - chomp $server_reply; - return; # return false - } - } while (/^[\d]+-/); + + while (my @sockets = $Sel->can_read($mailcfg{'timeout'})) { + return if (!@sockets); + # 16kByte is the maximum size of an SSL frame and because sysread + # returns data from only a single SSL frame you can guarantee that + # there are no pending data. + sysread($sockets[0], $buffer, 65535) || return; + $server_reply .= $buffer; + last if ($buffer =~ m/\n$/); + } + + print STDERR "<$server_reply" if $mailcfg{'debug'} > 9; + if ($server_reply =~ /^[45]/) { + chomp $server_reply; + return; # return false + } chomp $server_reply; return $server_reply; } @@ -260,13 +278,15 @@ sub sendmail { } $smtp = $mail{'Smtp'} || $mail{'Server'}; - unshift @{$mailcfg{'smtp'}}, $smtp if ($smtp and $mailcfg{'smtp'}->[0] ne $smtp); + $mailcfg{'smtp'}->[0] = $smtp if ($smtp and $mailcfg{'smtp'}->[0] ne $smtp); + + $encryption = $mail{'Encryption'} || $mail{'Encryption'}; # delete non-header keys, so we don't send them later as mail headers # I like this syntax, but it doesn't seem to work with AS port 5.003_07: # delete @mail{'Smtp', 'Server'}; # so instead: - delete $mail{'Smtp'}; delete $mail{'Server'}; + delete $mail{'Smtp'}; delete $mail{'Server'}; delete $mail{'Encryption'}; $mailcfg{'port'} = $mail{'Port'} || $mailcfg{'port'} || 25; delete $mail{'Port'}; @@ -343,48 +363,36 @@ sub sendmail { $localhost = hostname() || 'localhost'; foreach $server ( @{$mailcfg{'smtp'}} ) { - # open socket needs to be inside this foreach loop on Linux, - # otherwise all servers fail if 1st one fails !??! why? - unless ( socket S, AF_INET, SOCK_STREAM, scalar(getprotobyname 'tcp') ) { - return fail("socket failed ($!)") - } - - print "- trying $server\n" if $mailcfg{'debug'} > 1; + print STDERR "- trying $server\n" if $mailcfg{'debug'} > 9; $server =~ s/\s+//go; # remove spaces just in case of a typo # extract port if server name like "mail.domain.com:2525" $port = ($server =~ s/:(\d+)$//o) ? $1 : $mailcfg{'port'}; $smtp = $server; # save $server for use outside foreach loop - my $smtpaddr = inet_aton $server; - unless ($smtpaddr) { - $error .= "$server not found\n"; - next; # next server + # load IO::Socket SSL if needed + if ($encryption ne 'none') { + eval "require IO::Socket::SSL" || return fail("IO::Socket::SSL is not available"); } - my $retried = 0; # reset retries for each server - while ( ( not $connected = connect S, pack_sockaddr_in($port, $smtpaddr) ) - and ( $retried < $mailcfg{'retries'} ) - ) { - $retried++; - $error .= "connect to $server failed ($!)\n"; - print "- connect to $server failed ($!)\n" if $mailcfg{'debug'} > 1; - print "retrying in $mailcfg{'delay'} seconds...\n" if $mailcfg{'debug'} > 1; - sleep $mailcfg{'delay'}; + if ($encryption ne 'ssl') { + $S = new IO::Socket::INET(PeerPort => $port, PeerAddr => $server, Proto => 'tcp'); } - - if ( $connected ) { - print "- connected to $server\n" if $mailcfg{'debug'} > 3; + else { + $S = new IO::Socket::SSL(PeerPort => $port, PeerAddr => $server, Proto => 'tcp', SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE(), Domain => AF_INET); + } + if ( $S ) { + print STDERR "- connected to $server\n" if $mailcfg{'debug'} > 9; last; } else { $error .= "connect to $server failed\n"; - print "- connect to $server failed, next server...\n" if $mailcfg{'debug'} > 1; + print STDERR "- connect to $server failed, next server...\n" if $mailcfg{'debug'} > 9; next; # next server } } - unless ( $connected ) { + unless ( $S ) { return fail("connect to $smtp failed ($!) no (more) retries!") }; @@ -397,8 +405,9 @@ sub sendmail { ; } - my($oldfh) = select(S); $| = 1; select($oldfh); - + $Sel = new IO::Select() || return fail("IO::Select error"); + $Sel->add($S); + socket_read() || return fail("Connection error from $smtp on port $port ($_)"); socket_write("EHLO $localhost$CRLF") @@ -418,8 +427,37 @@ sub sendmail { || return fail("send HELO error (lost connection?)"); } - if ($auth) { - warn "AUTH requested\n" if ($mailcfg{debug} > 4); + # STARTTLS + if ($encryption eq 'starttls') { + defined($esmtp{'STARTTLS'}) + || return fail('STARTTLS not supported'); + socket_write("STARTTLS$CRLF") || return fail("send STARTTLS error"); + socket_read() + || return fail('STARTTLS error'); + IO::Socket::SSL->start_SSL($S, SSL_hostname => $server, SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE()) + || return fail("start_SSL failed"); + + # The client SHOULD send an EHLO command as the + # first command after a successful TLS negotiation. + socket_write("EHLO $localhost$CRLF") + || return fail("send EHLO error (lost connection?)"); + my $ehlo = socket_read(); + if ($ehlo) { + # The server MUST discard any knowledge + # obtained from the client. + %esmtp = (); + + # parse EHLO response + map { + s/^\d+[- ]//; + my ($k, $v) = split /\s+/, $_, 2; + $esmtp{$k} = $v || 1 if $k; + } split(/\n/, $ehlo); + } + } + + if (defined($auth) && $auth->{'user'} ne '') { + warn "AUTH requested\n" if ($mailcfg{debug} > 9); # reduce wanted methods to those supported my @methods = grep {$esmtp{'AUTH'}=~/(^|\s)$_(\s|$)/i} grep {$auth_support =~ /(^|\s)$_(\s|$)/i} @@ -480,9 +518,9 @@ sub sendmail { my $challenge = socket_read() || return fail("AUTH DIGEST-MD5 failed: $server_reply"); $challenge =~ s/^\d+\s+//; $challenge =~ s/[\r\n]+$//; - warn "\nCHALLENGE=", decode_base64($challenge), "\n" if ($mailcfg{debug} > 10); + warn "\nCHALLENGE=", decode_base64($challenge), "\n" if ($mailcfg{debug} > 9); my $response = _digest_md5($auth->{user}, $auth->{password}, decode_base64($challenge), $auth->{realm}); - warn "\nRESPONSE=$response\n" if ($mailcfg{debug} > 10); + warn "\nRESPONSE=$response\n" if ($mailcfg{debug} > 9); socket_write(encode_base64($response, ""), $CRLF) || return fail("AUTH DIGEST-MD5 failed: $server_reply"); my $status = socket_read() @@ -562,7 +600,7 @@ sub sendmail { socket_write("QUIT$CRLF") || return fail("send QUIT error"); socket_read(); - close S; + close $S; return 1; } # end sub sendmail diff --git a/pandora_server/lib/PandoraFMS/Tools.pm b/pandora_server/lib/PandoraFMS/Tools.pm index 36050e4275..ba15f03d24 100755 --- a/pandora_server/lib/PandoraFMS/Tools.pm +++ b/pandora_server/lib/PandoraFMS/Tools.pm @@ -140,6 +140,8 @@ our @EXPORT = qw( generate_agent_name_hash long_to_ip ip_to_long + get_enabled_servers + dateTimeToTimestamp ); # ID of the different servers @@ -518,7 +520,14 @@ sub pandora_sendmail { Smtp => $pa_config->{"mta_address"}, Port => $pa_config->{"mta_port"}, From => $pa_config->{"mta_from"}, + Encryption => $pa_config->{"mta_encryption"}, ); + + # Set the timeout. + $PandoraFMS::Sendmail::mailcfg{'timeout'} = $pa_config->{"tcp_timeout"}; + + # Enable debugging. + $PandoraFMS::Sendmail::mailcfg{'debug'} = $pa_config->{"verbosity"}; if (defined($content_type)) { $mail{'Content-Type'} = $content_type; @@ -535,15 +544,12 @@ sub pandora_sendmail { $mail{auth} = {user=>$pa_config->{"mta_user"}, password=>$pa_config->{"mta_pass"}, method=>$pa_config->{"mta_auth"}, required=>1 }; } - if (sendmail %mail) { - return; - } - else { - logger ($pa_config, "[ERROR] Sending email to $to_address with subject $subject", 1); - if (defined($Mail::Sendmail::error)){ - logger ($pa_config, "ERROR Code: $Mail::Sendmail::error", 5); + eval { + if (!sendmail(%mail)) { + logger ($pa_config, "[ERROR] Sending email to $to_address with subject $subject", 1); + logger ($pa_config, "ERROR Code: $Mail::Sendmail::error", 5) if (defined($Mail::Sendmail::error)); } - } + }; } ########################################################################## @@ -564,7 +570,8 @@ sub is_numeric { my $SIGN = qr{ [+-] }xms; my $NUMBER = qr{ ($SIGN?) ($DIGITS) }xms; if ( $val !~ /^${NUMBER}$/ ) { - return 0; #Non-numeric + #Non-numeric, or maybe... leave looks_like_number try + return looks_like_number($val); } else { return 1; #Numeric @@ -619,7 +626,7 @@ sub logger ($$;$) { $message = safe_output ($message); $level = 1 unless defined ($level); - return if ($level > $pa_config->{'verbosity'}); + return if (!defined ($pa_config->{'verbosity'}) || $level > $pa_config->{'verbosity'}); if (!defined($pa_config->{'log_file'})) { print strftime ("%Y-%m-%d %H:%M:%S", localtime()) . " [V". $level ."] " . $message . "\n"; @@ -635,19 +642,29 @@ sub logger ($$;$) { # Set the security level my $security_level = 'info'; if ($level < 2) { - $security = 'crit'; + $security_level = 'crit'; } elsif ($level < 5) { - $security = 'warn'; + $security_level = 'warn'; } openlog('pandora_server', 'ndelay', 'daemon'); syslog($security_level, $message); closelog(); } else { + # Obtain the script that invoke this log + my $parent_caller = ""; + $parent_caller = ( caller(2) )[1]; + if (defined $parent_caller) { + $parent_caller = (split '/', $parent_caller)[-1]; + $parent_caller =~ s/\.[^.]+$//; + $parent_caller = " ** " . $parent_caller . " **: "; + } else { + $parent_caller = " "; + } open (FILE, ">> $file") or die "[FATAL] Could not open logfile '$file'"; # Get an exclusive lock on the file (LOCK_EX) flock (FILE, 2); - print FILE strftime ("%Y-%m-%d %H:%M:%S", localtime()) . " " . (defined($pa_config->{'servername'}) ? $pa_config->{'servername'} : '') . " [V". $level ."] " . $message . "\n"; + print FILE strftime ("%Y-%m-%d %H:%M:%S", localtime()) . $parent_caller . (defined($pa_config->{'servername'}) ? $pa_config->{'servername'} : '') . " [V". $level ."] " . $message . "\n"; close (FILE); } } @@ -989,7 +1006,8 @@ sub load_average { $load_average = ((split(/\s+/, `/sbin/sysctl -n vm.loadavg`))[1]); } elsif ($OSNAME eq "MSWin32") { # Windows hasn't got load average. - $load_average = undef; + $load_average = `powershell "(Get-WmiObject win32_processor | Measure-Object -property LoadPercentage -Average).average"`; + chop($load_average); } # by default LINUX calls else { @@ -2049,6 +2067,25 @@ sub long_to_ip { return inet_ntoa pack("N", ($ip_long)); } +############################################################################### +# Returns a list with enabled servers. +############################################################################### +sub get_enabled_servers { + my $conf = shift; + + if (ref($conf) ne "HASH") { + return (); + } + + my @server_list = map { + if ($_ =~ /server$/i && $conf->{$_} > 0) { + $_ + } else { + } + } keys %{$conf}; + + return @server_list; +} # End of function declaration # End of defined Code diff --git a/pandora_server/pandora_server.redhat.spec b/pandora_server/pandora_server.redhat.spec index 547ef9e026..805efb4c41 100644 --- a/pandora_server/pandora_server.redhat.spec +++ b/pandora_server/pandora_server.redhat.spec @@ -2,8 +2,8 @@ # Pandora FMS Server # %define name pandorafms_server -%define version 7.0NG.738 -%define release 190913 +%define version 7.0NG.740 +%define release 191029 Summary: Pandora FMS Server Name: %{name} @@ -27,7 +27,7 @@ Requires: perl(DBI) perl(DBD::mysql) Requires: perl(HTTP::Request::Common) perl(LWP::Simple) perl(LWP::UserAgent) Requires: perl(XML::Simple) perl(XML::Twig) net-snmp-utils Requires: perl(NetAddr::IP) net-snmp net-tools -Requires: perl(IO::Socket::INET6) perl(Net::Telnet) +Requires: perl(IO::Socket::INET6) perl(IO::Socket::SSL) perl(Net::Telnet) Requires: nmap sudo perl(JSON) Requires: perl(Time::HiRes) perl(Encode::Locale) Requires: perl perl(Sys::Syslog) perl(HTML::Entities) perl(Geo::IP) diff --git a/pandora_server/pandora_server.spec b/pandora_server/pandora_server.spec index 68b47d82b0..e2eb323b24 100644 --- a/pandora_server/pandora_server.spec +++ b/pandora_server/pandora_server.spec @@ -2,8 +2,8 @@ # Pandora FMS Server # %define name pandorafms_server -%define version 7.0NG.738 -%define release 190913 +%define version 7.0NG.740 +%define release 191029 Summary: Pandora FMS Server Name: %{name} @@ -24,7 +24,7 @@ Provides: %{name}-%{version} Requires: perl-DBI perl-DBD-mysql perl-libwww-perl Requires: perl-NetAddr-IP net-snmp net-tools perl-XML-Twig Requires: nmap sudo perl-HTML-Tree perl-XML-Simple perl-Net-Telnet -Requires: perl-IO-Socket-INET6 perl-Socket6 snmp-mibs perl-JSON +Requires: perl-IO-Socket-INET6 perl-Socket6 perl-IO-Socket-SSL snmp-mibs perl-JSON Requires: perl-Encode-Locale perl-Geo-IP %description diff --git a/pandora_server/pandora_server_installer b/pandora_server/pandora_server_installer index 0197261987..6b1870fadf 100755 --- a/pandora_server/pandora_server_installer +++ b/pandora_server/pandora_server_installer @@ -8,8 +8,8 @@ # This code is licensed under GPL 2.0 license. # ********************************************************************** -PI_VERSION="7.0NG.738" -PI_BUILD="190913" +PI_VERSION="7.0NG.740" +PI_BUILD="191029" MODE=$1 if [ $# -gt 1 ]; then diff --git a/pandora_server/util/integria_rticket.pl b/pandora_server/util/integria_rticket.pl index 609dd516b0..f296fd9145 100644 --- a/pandora_server/util/integria_rticket.pl +++ b/pandora_server/util/integria_rticket.pl @@ -38,6 +38,7 @@ Where options: Optional parameters: [-priority ] : 10 Maintance, 0 Informative, 1 Low, 2 Medium, 3 Serious, 4 Very serious + [-owner ] : Free text [-desc ] : Free text [-type ] : Type ID (must exist in Integria IMS) [-inventory ] : Inventory ID (must exist in Integria IMS) @@ -94,6 +95,7 @@ sub tool_api_main () { my $ticket_name = ""; my $group_id = -1; my $ticket_priority = 0; + my $ticket_owner = ''; my $ticket_description = ''; my $ticket_type = ''; my $ticket_inventory = ''; @@ -155,6 +157,9 @@ sub tool_api_main () { if ($line eq '-priority') { $ticket_priority = $ARGV[$i + 1]; } + if ($line eq '-owner') { + $ticket_owner = $ARGV[$i + 1]; + } if ($line eq '-desc') { $ticket_description = $ARGV[$i + 1]; } @@ -193,6 +198,7 @@ sub tool_api_main () { $data_ticket = $ticket_name . "|;|" . $group_id . "|;|" . $ticket_priority . + "|;|" . $ticket_owner . "|;|" . $ticket_description . "|;|" . $ticket_inventory . "|;|" . $ticket_type . diff --git a/pandora_server/util/pandora_db.pl b/pandora_server/util/pandora_db.pl index 374b742a1c..a9cc09579b 100644 --- a/pandora_server/util/pandora_db.pl +++ b/pandora_server/util/pandora_db.pl @@ -34,7 +34,7 @@ use PandoraFMS::Config; use PandoraFMS::DB; # version: define current version -my $version = "7.0NG.738 PS190913"; +my $version = "7.0NG.740 PS191029"; # Pandora server configuration my %conf; diff --git a/pandora_server/util/pandora_manage.pl b/pandora_server/util/pandora_manage.pl index 53b18b8cd9..a3ffd61ecb 100755 --- a/pandora_server/util/pandora_manage.pl +++ b/pandora_server/util/pandora_manage.pl @@ -36,7 +36,7 @@ use Encode::Locale; Encode::Locale::decode_argv; # version: define current version -my $version = "7.0NG.738 PS190913"; +my $version = "7.0NG.740 PS191029"; # save program name for logging my $progname = basename($0); @@ -104,8 +104,8 @@ sub help_screen{ print "Available options for $param:\n\n" unless $param eq ''; print "AGENTS:\n\n" unless $param ne ''; help_screen_line('--create_agent', " \n\t [
    ]", 'Create agent'); - help_screen_line('--update_agent', ' ', "Update an agent field. The fields can be \n\t the following: agent_name, address, description, group_name, interval, os_name, disabled (0-1), \n\t parent_name, cascade_protection (0-1), icon_path, update_gis_data (0-1), custom_id"); - help_screen_line('--delete_agent', '', 'Delete agent'); + help_screen_line('--update_agent', ' []', "Update an agent field. The fields can be \n\t the following: agent_name, address, description, group_name, interval, os_name, disabled (0-1), \n\t parent_name, cascade_protection (0-1), icon_path, update_gis_data (0-1), custom_id"); + help_screen_line('--delete_agent', ' []', 'Delete agent'); help_screen_line('--disable_group', '', 'Disable agents from an entire group'); help_screen_line('--enable_group', '', 'Enable agents from an entire group'); help_screen_line('--create_group', ' [ ]', 'Create an agent group'); @@ -118,14 +118,14 @@ sub help_screen{ help_screen_line('--get_planned_downtimes_items', ' [ ]', 'Get all items of planned downtimes'); help_screen_line('--set_planned_downtimes_deleted', ' ', 'Deleted a planned downtime'); help_screen_line('--get_module_id', ' ', 'Get the id of an module'); - help_screen_line('--get_agent_group', '', 'Get the group name of an agent'); - help_screen_line('--get_agent_group_id', '', 'Get the group ID of an agent'); - help_screen_line('--get_agent_modules', '', 'Get the modules of an agent'); - help_screen_line('--get_agents', '[ ]', "Get \n\t list of agents with optative filter parameters"); - help_screen_line('--delete_conf_file', '', 'Delete a local conf of a given agent'); - help_screen_line('--clean_conf_file', '', "Clean a local conf of a given agent deleting all modules, \n\t policies, file collections and comments"); + help_screen_line('--get_agent_group', ' []', 'Get the group name of an agent'); + help_screen_line('--get_agent_group_id', ' []', 'Get the group ID of an agent'); + help_screen_line('--get_agent_modules', ' []', 'Get the modules of an agent'); + help_screen_line('--get_agents', '[ ]', "Get \n\t list of agents with optative filter parameters"); + help_screen_line('--delete_conf_file', ' []', 'Delete a local conf of a given agent'); + help_screen_line('--clean_conf_file', ' []', "Clean a local conf of a given agent deleting all modules, \n\t policies, file collections and comments"); help_screen_line('--get_bad_conf_files', '', 'Get the files bad configured (without essential tokens)'); - help_screen_line('--locate_agent', '', 'Search a agent into of nodes of metaconsole. Only Enterprise.'); + help_screen_line('--locate_agent', ' []', 'Search a agent into of nodes of metaconsole. Only Enterprise.'); help_screen_line('--migration_agent_queue', ' []', 'Migrate agent only metaconsole'); help_screen_line('--migration_agent', ' ', 'Is migrating the agent only metaconsole'); help_screen_line('--apply_module_template', ' ', 'Apply module template to agent'); @@ -139,29 +139,29 @@ sub help_screen{ help_screen_line('--set_disabled_and_standby', ' ', 'Overwrite and disable and standby status'); help_screen_line('--reset_agent_counts', '', 'Resets module counts and alert counts in the agents'); print "\nMODULES:\n\n" unless $param ne ''; - help_screen_line('--create_data_module', " [ \n\t \n\t \n\t \n\t \n\t ]", 'Add data server module to agent'); - help_screen_line('--create_web_module', " [ \n\t \n\t \n\t \n\t \n\t \n\t ].\n\t The valid data types are web_data, web_proc, web_content_data or web_content_string", 'Add web server module to agent'); - help_screen_line('--create_network_module', " \n\t [ \n\t \n\t \n\t \n\t \n\t ]", 'Add not snmp network module to agent'); - help_screen_line('--create_snmp_module', " \n\t [ \n\t \n\t \n\t \n\t \n\t + help_screen_line('--create_data_module', " [ \n\t \n\t \n\t \n\t \n\t ]", 'Add data server module to agent'); + help_screen_line('--create_web_module', " [ \n\t \n\t \n\t \n\t \n\t \n\t ].\n\t The valid data types are web_data, web_proc, web_content_data or web_content_string", 'Add web server module to agent'); + help_screen_line('--create_network_module', " \n\t [ \n\t \n\t \n\t \n\t \n\t ]", 'Add not snmp network module to agent'); + help_screen_line('--create_snmp_module', " \n\t [ \n\t \n\t \n\t \n\t \n\t ] \n\t \n\t ]", 'Add snmp network module to agent'); - help_screen_line('--create_plugin_module', " \n\t [ \n\t \n\t \n\t \n\t \n\t \n\t ]", 'Add plug-in module to agent'); + help_screen_line('--create_plugin_module', " \n\t [ \n\t \n\t \n\t \n\t \n\t \n\t ]", 'Add plug-in module to agent'); help_screen_line('--get_module_group', '[]', 'Dysplay all module groups'); help_screen_line('--create_module_group', ''); help_screen_line('--module_group_synch', " []", 'Synchronize metaconsole module groups'); - help_screen_line('--delete_module', 'Delete module from agent', ' '); - help_screen_line('--data_module', " \n\t []", 'Insert data to module'); - help_screen_line('--get_module_data', " []", "\n\t Show the data of a module in the last X seconds (interval) in CSV format"); - help_screen_line('--delete_data', '-m | -a | -g ', "Delete historic \n\t data of a module, the modules of an agent or the modules of the agents of a group"); - help_screen_line('--update_module', ' ', 'Update a module field'); + help_screen_line('--delete_module', 'Delete module from agent', ' []'); + help_screen_line('--data_module', " \n\t [ ]", 'Insert data to module'); + help_screen_line('--get_module_data', " [ ]", "\n\t Show the data of a module in the last X seconds (interval) in CSV format"); + help_screen_line('--delete_data', '-m | -a | -g []', "Delete historic \n\t data of a module, the modules of an agent or the modules of the agents of a group"); + help_screen_line('--update_module', ' []', 'Update a module field'); help_screen_line('--get_agents_module_current_data', '', "Get the agent and current data \n\t of all the modules with a given name"); - help_screen_line('--create_network_module_from_component', ' ', "Create a new network \n\t module from a network component"); + help_screen_line('--create_network_module_from_component', ' []', "Create a new network \n\t module from a network component"); help_screen_line('--create_network_component', " \n\t [ \n\t \n\t \n\t \n\t \n\t \n\t ]", "Create a new network component"); - help_screen_line('--create_synthetic', " ,,|, \n\t [ , | ,, ]", "Create a new Synthetic module"); + help_screen_line('--create_synthetic', " ,,|, \n\t [ , | ,, ]", "Create a new Synthetic module"); print "\nALERTS:\n\n" unless $param ne ''; - help_screen_line('--create_template_module', ' ', 'Add alert template to module'); - help_screen_line('--delete_template_module', ' ', 'Delete alert template from module'); - help_screen_line('--create_template_action', " \n\t [ ]', 'Add alert action to module-template"); - help_screen_line('--delete_template_action', " \n\t ", 'Delete alert action from module-template'); + help_screen_line('--create_template_module', ' []', 'Add alert template to module'); + help_screen_line('--delete_template_module', ' []', 'Delete alert template from module'); + help_screen_line('--create_template_action', " \n\t [ ]', 'Add alert action to module-template"); + help_screen_line('--delete_template_action', " \n\t []", 'Delete alert action from module-template'); help_screen_line('--disable_alerts', '', 'Disable alerts in all groups (system wide)'); help_screen_line('--enable_alerts', '', 'Enable alerts in all groups (system wide)'); help_screen_line('--create_alert_template', " \n\t [ \n\t \n\t \n\t ]", 'Create alert template'); @@ -175,7 +175,7 @@ sub help_screen{ help_screen_line('--create_special_day', " ", 'Create special day'); help_screen_line('--delete_special_day', '', 'Delete special day'); help_screen_line('--update_special_day', " ", 'Update a field of a special day'); - help_screen_line('--create_data_module_from_local_component', ' ', "Create a new data \n\t module from a local component"); + help_screen_line('--create_data_module_from_local_component', ' []', "Create a new data \n\t module from a local component"); help_screen_line('--create_local_component', " [ \n\t \n\t \n\t \n\t \n\t \n\t \n\t \n\t ]", 'Create local component'); print "\nUSERS:\n\n" unless $param ne ''; @@ -193,17 +193,17 @@ sub help_screen{ help_screen_line('--disable_double_auth', '', 'Disable the double authentication for the specified user'); help_screen_line('--meta_synch_user', " [ \n\t ]", 'Synchronize metaconsole users'); print "\nEVENTS:\n\n" unless $param ne ''; - help_screen_line('--create_event', " [ \n\t \n\t \n\t ]", 'Add event'); - help_screen_line('--validate_event', " \n\t ", 'Validate events'); - help_screen_line('--validate_event_id', '', 'Validate event given a event id'); - help_screen_line('--get_event_info', '[]', 'Show info about a event given a event id'); - help_screen_line('--add_event_comment', ' ', 'Add event\'s comment'); + help_screen_line('--create_event', " [ \n\t \n\t \n\t ]", 'Add event'); + help_screen_line('--validate_event', " \n\t []", 'Validate events'); + help_screen_line('--validate_event_id', '', 'Validate event given a event id'); + help_screen_line('--get_event_info', '[]', 'Show info about a event given a event id'); + help_screen_line('--add_event_comment', ' ', 'Add event\'s comment'); print "\nINCIDENTS:\n\n" unless $param ne ''; help_screen_line('--create_incident', " <description> <origin> <status> <priority 0 for Informative, \n\t 1 for Low, 2 for Medium, 3 for Serious, 4 for Very serious or 5 for Maintenance>\n\t <group> [<owner>]", 'Create incidents'); print "\nPOLICIES:\n\n" unless $param ne ''; help_screen_line('--apply_policy', '<id_policy> [<id_agent> <name(boolean)> <id_server>]', 'Force apply a policy in an agent'); help_screen_line('--apply_all_policies', '', 'Force apply to all the policies'); - help_screen_line('--add_agent_to_policy', '<agent_name> <policy_name>', 'Add an agent to a policy'); + help_screen_line('--add_agent_to_policy', '<agent_name> <policy_name> [<use_alias>]', 'Add an agent to a policy'); help_screen_line('--remove_agent_from_policy', '<policy_id> <agent_id>', 'Delete an agent to a policy'); help_screen_line('--delete_not_policy_modules', '', 'Delete all modules without policy from configuration file'); help_screen_line('--disable_policy_alerts', '<policy_name>', 'Disable all the alerts of a policy'); @@ -218,7 +218,7 @@ sub help_screen{ help_screen_line('--add_collection_to_policy', "<policy_name> <collection_name>"); help_screen_line('--validate_policy_alerts', '<policy_name>', 'Validate the alerts of a given policy'); help_screen_line('--get_policy_modules', '<policy_name>', 'Get the modules of a policy'); - help_screen_line('--get_policies', '[<agent_name>]', "Get all the policies (without parameters) or \n\tthe policies of a given agent (agent name as parameter)"); + help_screen_line('--get_policies', '[<agent_name> <use_alias>]', "Get all the policies (without parameters) or \n\tthe policies of a given agent (agent name as parameter)"); help_screen_line('--recreate_collection', '<collection_id>', 'Recreate the files of a collection'); print "\nNETFLOW:\n\n" unless $param ne ''; @@ -1135,19 +1135,26 @@ sub cli_create_agent() { ############################################################################## sub cli_delete_agent() { - my $agent_name = @ARGV[2]; + my ($agent_name,$use_alias) = @ARGV[2..3]; + + my @id_agents; + my $id_agent; $agent_name = decode_entities($agent_name); - + if (is_metaconsole($conf) == 1) { - my $agents_groups = enterprise_hook('get_metaconsole_agent',[$dbh, $agent_name]); - - if (scalar(@{$agents_groups}) != 0) { - foreach my $agent (@{$agents_groups}) { - my $return = enterprise_hook('delete_metaconsole_agent',[$dbh,$agent->{'id_agente'}]); - print_log "[INFO] Deleting agent '$agent_name' \n\n"; + if (not defined $use_alias) { + my $agents_groups = enterprise_hook('get_metaconsole_agent',[$dbh, $agent_name]); + + if (scalar(@{$agents_groups}) != 0) { + foreach my $agent (@{$agents_groups}) { + my $return = enterprise_hook('delete_metaconsole_agent',[$dbh,$agent->{'id_agente'}]); + print_log "[INFO] Deleting agent '$agent_name' \n\n"; + } } } + + my $servers = enterprise_hook('get_metaconsole_setup_servers',[$dbh]); my @servers_id = split(',',$servers); my @list_servers; @@ -1155,24 +1162,58 @@ sub cli_delete_agent() { foreach my $server (@servers_id) { my $dbh_metaconsole = enterprise_hook('get_node_dbh',[$conf, $server, $dbh]); - my $id_agent = get_agent_id($dbh_metaconsole,$agent_name); + my @id_agents; + my $id_agent; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh_metaconsole,$agent_name); + + foreach my $id (@id_agents) { + + if ($id->{'id_agente'} == -1) { + next; + } + else { + print_log "[INFO] Deleting agent '$id->{'nombre'}' in ID server: '$server'\n\n"; + pandora_delete_agent($dbh_metaconsole,$id->{'id_agente'},$conf); + } + } + } else { + $id_agent = get_agent_id($dbh_metaconsole,$agent_name); + + if ($id_agent == -1) { + next; + } + else { + print_log "[INFO] Deleting agent '$agent_name' in ID server: '$server'\n\n"; + pandora_delete_agent($dbh_metaconsole,$id_agent,$conf); + } + } + - if ($id_agent == -1) { - next; - } - else { - print_log "[INFO] Deleting agent '$agent_name' in ID server: '$server'\n\n"; - pandora_delete_agent($dbh_metaconsole,$id_agent,$conf); - } } } else { - - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); - - print_log "[INFO] Deleting agent '$agent_name'\n\n"; - pandora_delete_agent($dbh,$id_agent,$conf); + my @id_agents; + my $id_agent; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + } else { + $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + } + + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + exist_check($id->{'id_agente'},'agent',$agent_name); + print_log "[INFO] Deleting agent '$id->{'nombre'}'\n\n"; + pandora_delete_agent($dbh,$id->{'id_agente'},$conf); + } + } else { + print_log "[INFO] Deleting agent '$agent_name'\n\n"; + pandora_delete_agent($dbh,$id_agent,$conf); + } } } @@ -1290,14 +1331,14 @@ sub cli_create_data_module($) { $min,$max,$post_process, $interval, $warning_min, $warning_max, $critical_min, $critical_max, $history_data, $definition_file, $configuration_data, $warning_str, $critical_str, $enable_unknown_events, $ff_threshold, $each_ff, $ff_threshold_normal, $ff_threshold_warning, $ff_threshold_critical, $ff_timeout, - $warning_inverse, $critical_inverse, $critical_instructions, $warning_instructions, $unknown_instructions); + $warning_inverse, $critical_inverse, $critical_instructions, $warning_instructions, $unknown_instructions, $use_alias); if ($in_policy == 0) { ($module_name, $module_type, $agent_name, $description, $module_group, $min,$max,$post_process, $interval, $warning_min, $warning_max, $critical_min, $critical_max, $history_data, $definition_file, $warning_str, $critical_str, $enable_unknown_events, $ff_threshold, $each_ff, $ff_threshold_normal, $ff_threshold_warning, $ff_threshold_critical, $ff_timeout, - $warning_inverse, $critical_inverse, $critical_instructions, $warning_instructions, $unknown_instructions) = @ARGV[2..30]; + $warning_inverse, $critical_inverse, $critical_instructions, $warning_instructions, $unknown_instructions, $use_alias) = @ARGV[2..31]; } else { ($policy_name, $module_name, $module_type, $description, $module_group, @@ -1311,6 +1352,7 @@ sub cli_create_data_module($) { my $module_type_def; my $agent_id; + my @id_agents; my $policy_id; my $disabled_types_event = {}; @@ -1323,13 +1365,22 @@ sub cli_create_data_module($) { my $disabled_types_event_json = encode_json($disabled_types_event); if ($in_policy == 0) { - $agent_id = get_agent_id($dbh,$agent_name); - exist_check($agent_id,'agent',$agent_name); - - my $module_exists = get_agent_module_id($dbh, $module_name, $agent_id); - non_exist_check($module_exists, 'module name', $module_name); - - #~ print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + exist_check($id->{'id_agente'},'agent',$agent_name); + + my $module_exists = get_agent_module_id($dbh, $module_name, $id->{'id_agente'}); + non_exist_check($module_exists, 'module name', $module_name); + } + } else { + $agent_id = get_agent_id($dbh,$agent_name); + exist_check($agent_id,'agent',$agent_name); + + my $module_exists = get_agent_module_id($dbh, $module_name, $agent_id); + non_exist_check($module_exists, 'module name', $module_name); + } } else { $policy_id = enterprise_hook('get_policy_id',[$dbh, safe_input($policy_name)]); @@ -1343,44 +1394,91 @@ sub cli_create_data_module($) { $module_name_def = $module_name; $module_type_def = $module_type; - # If the module is local and is not to policy, we add it to the conf file - if (defined($definition_file) && (-e $definition_file) && (-e $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf')){ - open (FILE, $definition_file); - my @file = <FILE>; - my $definition = join("", @file); - close (FILE); - - # If the parameter name or type and the definition file name or type - # dont match will be set the file definitions - open (FILE, $definition_file); - while (<FILE>) { - chomp; - my ($key, $val) = split / /,2; - if ($key eq 'module_name') { - $module_name_def = $val; - } - if ($key eq 'module_type') { - $module_type_def = $val; + + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + # If the module is local and is not to policy, we add it to the conf file + if (defined($definition_file) && (-e $definition_file) && (-e $conf->{incomingdir}.'/conf/'.md5($id->{'nombre'}).'.conf')){ + open (FILE, $definition_file); + my @file = <FILE>; + my $definition = join("", @file); + close (FILE); + + # If the parameter name or type and the definition file name or type + # dont match will be set the file definitions + open (FILE, $definition_file); + while (<FILE>) { + chomp; + my ($key, $val) = split / /,2; + if ($key eq 'module_name') { + $module_name_def = $val; + } + if ($key eq 'module_type') { + $module_type_def = $val; + } + } + close (FILE); + + open (FILE, $conf->{incomingdir}.'/conf/'.md5($id->{'nombre'}).'.conf'); + my @file = <FILE>; + my $conf_file = join("", @file); + close(FILE); + + open FILE, "> ".$conf->{incomingdir}.'/conf/'.md5($id->{'nombre'}).'.conf'; + print FILE "$conf_file\n$definition"; + close(FILE); + + enterprise_hook('pandora_update_md5_file', [$conf, $id->{'nombre'}]); } } - close (FILE); - - open (FILE, $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'); - my @file = <FILE>; - my $conf_file = join("", @file); - close(FILE); - - open FILE, "> ".$conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'; - print FILE "$conf_file\n$definition"; - close(FILE); - - enterprise_hook('pandora_update_md5_file', [$conf, $agent_name]); + } else { + # If the module is local and is not to policy, we add it to the conf file + if (defined($definition_file) && (-e $definition_file) && (-e $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf')){ + open (FILE, $definition_file); + my @file = <FILE>; + my $definition = join("", @file); + close (FILE); + + # If the parameter name or type and the definition file name or type + # dont match will be set the file definitions + open (FILE, $definition_file); + while (<FILE>) { + chomp; + my ($key, $val) = split / /,2; + if ($key eq 'module_name') { + $module_name_def = $val; + } + if ($key eq 'module_type') { + $module_type_def = $val; + } + } + close (FILE); + + open (FILE, $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'); + my @file = <FILE>; + my $conf_file = join("", @file); + close(FILE); + + open FILE, "> ".$conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'; + print FILE "$conf_file\n$definition"; + close(FILE); + + enterprise_hook('pandora_update_md5_file', [$conf, $agent_name]); + } } if ($in_policy == 0) { - my $module_exists = get_agent_module_id($dbh, $module_name_def, $agent_id); - non_exist_check($module_exists, 'module name', $module_name_def); - print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + my $module_exists = get_agent_module_id($dbh, $module_name_def, $id->{'id_agente'}); + non_exist_check($module_exists, 'module name', $module_name_def); + print_log "[INFO] Adding module '$module_name' to agent '$id->{'nombre'}'\n\n"; + } + } else { + my $module_exists = get_agent_module_id($dbh, $module_name_def, $agent_id); + non_exist_check($module_exists, 'module name', $module_name_def); + print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + } } else { my $policy_module_exist = enterprise_hook('get_policy_module_id',[$dbh, $policy_id, $module_name_def]); @@ -1398,7 +1496,6 @@ sub cli_create_data_module($) { print_log "[INFO] The module name has been forced to '$module_name' by the definition file\n\n"; } - # The get_module_id has wrong name. Change in future my $module_type_id = get_module_id($dbh,$module_type); exist_check($module_type_id,'module type',$module_type); @@ -1417,10 +1514,13 @@ sub cli_create_data_module($) { my %parameters; $parameters{'id_tipo_modulo'} = $module_type_id; - + if ($in_policy == 0) { $parameters{'nombre'} = safe_input($module_name); - $parameters{'id_agente'} = $agent_id; + + if (not defined $use_alias) { + $parameters{'id_agente'} = $agent_id; + } } else { $parameters{'name'} = safe_input($module_name); @@ -1464,7 +1564,14 @@ sub cli_create_data_module($) { $parameters{'unknown_instructions'} = $unknown_instructions unless !defined ($unknown_instructions); if ($in_policy == 0) { - pandora_create_module_from_hash ($conf, \%parameters, $dbh); + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + $parameters{'id_agente'} = $id->{'id_agente'}; + pandora_create_module_from_hash ($conf, \%parameters, $dbh); + } + } else { + pandora_create_module_from_hash ($conf, \%parameters, $dbh); + } } else { enterprise_hook('pandora_create_policy_module_from_hash', [$conf, \%parameters, $dbh]); @@ -1483,7 +1590,7 @@ sub cli_create_web_module($) { $critical_max, $history_data, $retries, $requests, $agent_browser_id, $auth_server, $auth_realm, $definition_file, $proxy_url, $proxy_auth_login, $proxy_auth_password, $configuration_data, $warning_str, $critical_str, $enable_unknown_events, $ff_threshold, $each_ff, $ff_threshold_normal, $ff_threshold_warning, $ff_threshold_critical, $ff_timeout, - $warning_inverse, $critical_inverse, $critical_instructions, $warning_instructions, $unknown_instructions); + $warning_inverse, $critical_inverse, $critical_instructions, $warning_instructions, $unknown_instructions, $use_alias); if ($in_policy == 0) { ($module_name, $module_type, $agent_name, $description, $module_group, @@ -1491,7 +1598,7 @@ sub cli_create_web_module($) { $critical_max, $history_data, $retries, $requests, $agent_browser_id, $auth_server, $auth_realm, $definition_file, $proxy_url, $proxy_auth_login, $proxy_auth_password, $warning_str, $critical_str, $enable_unknown_events, $ff_threshold, $each_ff, $ff_threshold_normal, $ff_threshold_warning, $ff_threshold_critical, $ff_timeout, - $warning_inverse, $critical_inverse, $critical_instructions, $warning_instructions, $unknown_instructions) = @ARGV[2..38]; + $warning_inverse, $critical_inverse, $critical_instructions, $warning_instructions, $unknown_instructions, $use_alias) = @ARGV[2..39]; } else { ($policy_name, $module_name, $module_type, $description, $module_group, @@ -1506,6 +1613,7 @@ sub cli_create_web_module($) { my $module_type_def; my $agent_id; + my @id_agents; my $policy_id; my $disabled_types_event = {}; @@ -1518,13 +1626,22 @@ sub cli_create_web_module($) { my $disabled_types_event_json = encode_json($disabled_types_event); if ($in_policy == 0) { - $agent_id = get_agent_id($dbh,$agent_name); - exist_check($agent_id,'agent',$agent_name); - - my $module_exists = get_agent_module_id($dbh, $module_name, $agent_id); - non_exist_check($module_exists, 'module name', $module_name); - - #~ print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + exist_check($id->{'id_agente'},'agent',$agent_name); + + my $module_exists = get_agent_module_id($dbh, $module_name, $id->{'id_agente'}); + non_exist_check($module_exists, 'module name', $module_name); + } + } else { + $agent_id = get_agent_id($dbh,$agent_name); + exist_check($agent_id,'agent',$agent_name); + + my $module_exists = get_agent_module_id($dbh, $module_name, $agent_id); + non_exist_check($module_exists, 'module name', $module_name); + } } else { $policy_id = enterprise_hook('get_policy_id',[$dbh, safe_input($policy_name)]); @@ -1538,44 +1655,90 @@ sub cli_create_web_module($) { $module_name_def = $module_name; $module_type_def = $module_type; + # If the module is local and is not to policy, we add it to the conf file - if (defined($definition_file) && (-e $definition_file) && (-e $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf')){ - open (FILE, $definition_file); - my @file = <FILE>; - my $definition = join("", @file); - close (FILE); - - # If the parameter name or type and the definition file name or type - # dont match will be set the file definitions - open (FILE, $definition_file); - while (<FILE>) { - chomp; - my ($key, $val) = split / /; - if ($key eq 'module_name') { - $module_name_def = $val; - } - if ($key eq 'module_type') { - $module_type_def = $val; + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + if (defined($definition_file) && (-e $definition_file) && (-e $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf')){ + open (FILE, $definition_file); + my @file = <FILE>; + my $definition = join("", @file); + close (FILE); + + # If the parameter name or type and the definition file name or type + # dont match will be set the file definitions + open (FILE, $definition_file); + while (<FILE>) { + chomp; + my ($key, $val) = split / /; + if ($key eq 'module_name') { + $module_name_def = $val; + } + if ($key eq 'module_type') { + $module_type_def = $val; + } + } + close (FILE); + + #open (FILE, $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'); + #my @file = <FILE>; + #my $conf_file = join("", @file); + #close(FILE); + + #open FILE, "> ".$conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'; + #print FILE "$conf_file\n$definition"; + #close(FILE); + + enterprise_hook('pandora_update_md5_file', [$conf, $agent_name]); } } - close (FILE); - - #open (FILE, $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'); - #my @file = <FILE>; - #my $conf_file = join("", @file); - #close(FILE); - - #open FILE, "> ".$conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'; - #print FILE "$conf_file\n$definition"; - #close(FILE); - - enterprise_hook('pandora_update_md5_file', [$conf, $agent_name]); + } else { + if (defined($definition_file) && (-e $definition_file) && (-e $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf')){ + open (FILE, $definition_file); + my @file = <FILE>; + my $definition = join("", @file); + close (FILE); + + # If the parameter name or type and the definition file name or type + # dont match will be set the file definitions + open (FILE, $definition_file); + while (<FILE>) { + chomp; + my ($key, $val) = split / /; + if ($key eq 'module_name') { + $module_name_def = $val; + } + if ($key eq 'module_type') { + $module_type_def = $val; + } + } + close (FILE); + + #open (FILE, $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'); + #my @file = <FILE>; + #my $conf_file = join("", @file); + #close(FILE); + + #open FILE, "> ".$conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'; + #print FILE "$conf_file\n$definition"; + #close(FILE); + + enterprise_hook('pandora_update_md5_file', [$conf, $agent_name]); + } } - + if ($in_policy == 0) { - my $module_exists = get_agent_module_id($dbh, $module_name_def, $agent_id); - non_exist_check($module_exists, 'module name', $module_name_def); - print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + my $module_exists = get_agent_module_id($dbh, $module_name_def, $id->{'id_agente'}); + non_exist_check($module_exists, 'module name', $module_name_def); + print_log "[INFO] Adding module '$module_name' to agent '$id->{'nombre'}'\n\n"; + } + } else { + my $module_exists = get_agent_module_id($dbh, $module_name_def, $agent_id); + non_exist_check($module_exists, 'module name', $module_name_def); + print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + } } else { my $policy_module_exist = enterprise_hook('get_policy_module_id',[$dbh, $policy_id, $module_name_def]); @@ -1615,7 +1778,10 @@ sub cli_create_web_module($) { if ($in_policy == 0) { $parameters{'nombre'} = safe_input($module_name); - $parameters{'id_agente'} = $agent_id; + + if (not defined $use_alias) { + $parameters{'id_agente'} = $agent_id; + } } else { $parameters{'name'} = safe_input($module_name); @@ -1672,14 +1838,21 @@ sub cli_create_web_module($) { if ($in_policy == 0) { - pandora_create_module_from_hash ($conf, \%parameters, $dbh); + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + $parameters{'id_agente'} = $id->{'id_agente'}; + pandora_create_module_from_hash ($conf, \%parameters, $dbh); + } + } else { + pandora_create_module_from_hash ($conf, \%parameters, $dbh); + } } else { enterprise_hook('pandora_create_policy_module_from_hash', [$conf, \%parameters, $dbh]); } #Begin Insert module definition from file_definition in bd - if (defined($definition_file)){ + if (defined($definition_file)){ open(my $fh, '<', $definition_file) or die($!); my @lines = <$fh>; @@ -1766,21 +1939,50 @@ sub cli_module_group_synch() { ############################################################################## sub cli_create_network_module_from_component() { - my ($agent_name, $component_name) = @ARGV[2..3]; - - my $agent_id = get_agent_id($dbh,$agent_name); - exist_check($agent_id,'agent',$agent_name); - - my $nc_id = pandora_get_network_component_id($dbh, $component_name); - exist_check($nc_id,'network component',$component_name); - - my $module_exists = get_agent_module_id($dbh, $component_name, $agent_id); - non_exist_check($module_exists, 'module name', $component_name); - - # Get network component data - my $component = get_db_single_row ($dbh, 'SELECT * FROM tnetwork_component WHERE id_nc = ?', $nc_id); - - pandora_create_module_from_network_component ($conf, $component, $agent_id, $dbh); + my ($agent_name, $component_name, $use_alias) = @ARGV[2..4]; + + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + my $agent_id; + my $module_exists; + my $component; + my $nc_id; + + foreach my $id (@id_agents) { + $agent_id = $id->{'id_agente'}; + exist_check($agent_id,'agent',$agent_name); + + $nc_id = pandora_get_network_component_id($dbh, $component_name); + exist_check($nc_id,'network component',$component_name); + + # Get network component data + $component = get_db_single_row ($dbh, 'SELECT * FROM tnetwork_component WHERE id_nc = ?', $nc_id); + + my $module_exists = get_agent_module_id($dbh, $component_name, $agent_id); + non_exist_check($module_exists, 'module name', $component_name); + + print_log "[INFO] Creating module from component '$component_name'\n\n"; + + pandora_create_module_from_network_component ($conf, $component, $agent_id, $dbh); + } + } else { + my $nc_id = pandora_get_network_component_id($dbh, $component_name); + exist_check($nc_id,'network component',$component_name); + + # Get network component data + my $component = get_db_single_row ($dbh, 'SELECT * FROM tnetwork_component WHERE id_nc = ?', $nc_id); + + my $agent_id = get_agent_id($dbh,$agent_name); + exist_check($agent_id,'agent',$agent_name); + + my $module_exists = get_agent_module_id($dbh, $component_name, $agent_id); + non_exist_check($module_exists, 'module name', $component_name); + + + print_log "[INFO] Creating module from component '$component_name'\n\n"; + + pandora_create_module_from_network_component ($conf, $component, $agent_id, $dbh); + } } ############################################################################## @@ -1831,7 +2033,7 @@ sub cli_create_network_module($) { $module_group, $min, $max, $post_process, $interval, $warning_min, $warning_max, $critical_min, $critical_max, $history_data, $ff_threshold, $warning_str, $critical_str, $enable_unknown_events, $each_ff, $ff_threshold_normal, $ff_threshold_warning, $ff_threshold_critical, $timeout, $retries, $critical_instructions, - $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse); + $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse, $use_alias); if ($in_policy == 0) { ($module_name, $module_type, $agent_name, $module_address, $module_port, $description, @@ -1839,7 +2041,7 @@ sub cli_create_network_module($) { $critical_max, $history_data, $ff_threshold, $warning_str, $critical_str, $enable_unknown_events, $each_ff, $ff_threshold_normal, $ff_threshold_warning, $ff_threshold_critical, $timeout, $retries,$critical_instructions, $warning_instructions, $unknown_instructions, - $warning_inverse, $critical_inverse) = @ARGV[2..32]; + $warning_inverse, $critical_inverse, $use_alias) = @ARGV[2..33]; } else { ($policy_name, $module_name, $module_type, $module_port, $description, @@ -1849,10 +2051,12 @@ sub cli_create_network_module($) { $ff_threshold_critical, $timeout, $retries, $critical_instructions, $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse) = @ARGV[2..31]; } - + my $module_name_def; my $module_type_def; + my $agent_id; + my @id_agents; my $policy_id; my $disabled_types_event = {}; @@ -1865,13 +2069,26 @@ sub cli_create_network_module($) { my $disabled_types_event_json = encode_json($disabled_types_event); if ($in_policy == 0) { - $agent_id = get_agent_id($dbh,$agent_name); - exist_check($agent_id,'agent',$agent_name); - - my $module_exists = get_agent_module_id($dbh, $module_name, $agent_id); - non_exist_check($module_exists, 'module name', $module_name); - - print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + exist_check($id->{'id_agente'},'agent',$agent_name); + + my $module_exists = get_agent_module_id($dbh, $module_name, $id->{'id_agente'}); + non_exist_check($module_exists, 'module name', $module_name); + + print_log "[INFO] Adding module '$module_name' to agent '$id->{'nombre'}'\n\n"; + } + } else { + $agent_id = get_agent_id($dbh,$agent_name); + exist_check($agent_id,'agent',$agent_name); + + my $module_exists = get_agent_module_id($dbh, $module_name, $agent_id); + non_exist_check($module_exists, 'module name', $module_name); + + print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + } } else { $policy_id = enterprise_hook('get_policy_id',[$dbh, safe_input($policy_name)]); @@ -1921,7 +2138,11 @@ sub cli_create_network_module($) { if ($in_policy == 0) { $parameters{'nombre'} = safe_input($module_name); - $parameters{'id_agente'} = $agent_id; + + if (not defined $use_alias) { + $parameters{'id_agente'} = $agent_id; + } + $parameters{'ip_target'} = $module_address; } else { @@ -1966,7 +2187,14 @@ sub cli_create_network_module($) { $parameters{'warning_inverse'} = $warning_inverse unless !defined ($warning_inverse); if ($in_policy == 0) { - pandora_create_module_from_hash ($conf, \%parameters, $dbh); + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + $parameters{'id_agente'} = $id->{'id_agente'}; + pandora_create_module_from_hash ($conf, \%parameters, $dbh); + } + } else { + pandora_create_module_from_hash ($conf, \%parameters, $dbh); + } } else { enterprise_hook('pandora_create_policy_module_from_hash', [$conf, \%parameters, $dbh]); @@ -1985,7 +2213,7 @@ sub cli_create_snmp_module($) { $warning_max, $critical_min, $critical_max, $history_data, $snmp3_priv_method, $snmp3_priv_pass, $snmp3_sec_level, $snmp3_auth_method, $snmp3_auth_user, $snmp3_auth_pass, $ff_threshold, $warning_str, $critical_str, $enable_unknown_events, $each_ff, $ff_threshold_normal, $ff_threshold_warning, $ff_threshold_critical, $timeout, $retries, - $critical_instructions, $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse); + $critical_instructions, $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse, $use_alias); if ($in_policy == 0) { ($module_name, $module_type, $agent_name, $module_address, $module_port, $version, $community, @@ -1993,7 +2221,7 @@ sub cli_create_snmp_module($) { $warning_max, $critical_min, $critical_max, $history_data, $snmp3_priv_method, $snmp3_priv_pass, $snmp3_sec_level, $snmp3_auth_method, $snmp3_auth_user, $snmp3_auth_pass, $ff_threshold, $warning_str, $critical_str, $enable_unknown_events, $each_ff, $ff_threshold_normal, $ff_threshold_warning, $ff_threshold_critical, $timeout, $retries, - $critical_instructions, $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse) = @ARGV[2..41]; + $critical_instructions, $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse, $use_alias) = @ARGV[2..42]; } else { ($policy_name, $module_name, $module_type, $module_port, $version, $community, @@ -2006,7 +2234,9 @@ sub cli_create_snmp_module($) { my $module_name_def; my $module_type_def; + my $agent_id; + my @id_agents; my $policy_id; my $disabled_types_event = {}; @@ -2019,13 +2249,26 @@ sub cli_create_snmp_module($) { my $disabled_types_event_json = encode_json($disabled_types_event); if ($in_policy == 0) { - $agent_id = get_agent_id($dbh,$agent_name); - exist_check($agent_id,'agent',$agent_name); - - my $module_exists = get_agent_module_id($dbh, $module_name, $agent_id); - non_exist_check($module_exists, 'module name', $module_name); - - print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + exist_check($id->{'id_agente'},'agent',$agent_name); + + my $module_exists = get_agent_module_id($dbh, $module_name, $id->{'id_agente'}); + non_exist_check($module_exists, 'module name', $module_name); + + print_log "[INFO] Adding module '$module_name' to agent '$id->{'nombre'}'\n\n"; + } + } else { + $agent_id = get_agent_id($dbh,$agent_name); + exist_check($agent_id,'agent',$agent_name); + + my $module_exists = get_agent_module_id($dbh, $module_name, $agent_id); + non_exist_check($module_exists, 'module name', $module_name); + + print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + } } else { $policy_id = enterprise_hook('get_policy_id',[$dbh, safe_input($policy_name)]); @@ -2064,7 +2307,11 @@ sub cli_create_snmp_module($) { if ($in_policy == 0) { $parameters{'nombre'} = safe_input($module_name); - $parameters{'id_agente'} = $agent_id; + + if (not defined $use_alias) { + $parameters{'id_agente'} = $agent_id; + } + $parameters{'ip_target'} = $module_address; } else { @@ -2125,7 +2372,14 @@ sub cli_create_snmp_module($) { $parameters{'warning_inverse'} = $warning_inverse unless !defined ($warning_inverse); if ($in_policy == 0) { - pandora_create_module_from_hash ($conf, \%parameters, $dbh); + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + $parameters{'id_agente'} = $id->{'id_agente'}; + pandora_create_module_from_hash ($conf, \%parameters, $dbh); + } + } else { + pandora_create_module_from_hash ($conf, \%parameters, $dbh); + } } else { enterprise_hook('pandora_create_policy_module_from_hash', [$conf, \%parameters, $dbh]); @@ -2144,7 +2398,7 @@ sub cli_create_plugin_module($) { $interval, $warning_min, $warning_max, $critical_min, $critical_max, $history_data, $ff_threshold, $warning_str, $critical_str, $enable_unknown_events, $each_ff, $ff_threshold_normal, $ff_threshold_warning, $ff_threshold_critical, $timeout, - $critical_instructions, $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse); + $critical_instructions, $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse, $use_alias); if ($in_policy == 0) { ($module_name, $module_type, $agent_name, $module_address, $module_port, $plugin_name, @@ -2152,7 +2406,7 @@ sub cli_create_plugin_module($) { $interval, $warning_min, $warning_max, $critical_min, $critical_max, $history_data, $ff_threshold, $warning_str, $critical_str, $enable_unknown_events, $each_ff, $ff_threshold_normal, $ff_threshold_warning, $ff_threshold_critical, $timeout, - $critical_instructions, $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse) = @ARGV[2..35]; + $critical_instructions, $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse, $use_alias) = @ARGV[2..36]; } else { ($policy_name, $module_name, $module_type, $module_port, $plugin_name, @@ -2162,10 +2416,12 @@ sub cli_create_plugin_module($) { $each_ff, $ff_threshold_normal, $ff_threshold_warning, $ff_threshold_critical, $timeout, $critical_instructions, $warning_instructions, $unknown_instructions, $warning_inverse, $critical_inverse) = @ARGV[2..34]; } - + my $module_name_def; my $module_type_def; + my $agent_id; + my @id_agents; my $policy_id; my $disabled_types_event = {}; @@ -2178,13 +2434,26 @@ sub cli_create_plugin_module($) { my $disabled_types_event_json = encode_json($disabled_types_event); if ($in_policy == 0) { - $agent_id = get_agent_id($dbh,$agent_name); - exist_check($agent_id,'agent',$agent_name); - - my $module_exists = get_agent_module_id($dbh, $module_name, $agent_id); - non_exist_check($module_exists, 'module name', $module_name); - - print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + exist_check($id->{'id_agente'},'agent',$agent_name); + + my $module_exists = get_agent_module_id($dbh, $module_name, $id->{'id_agente'}); + non_exist_check($module_exists, 'module name', $module_name); + + print_log "[INFO] Adding module '$module_name' to agent '$id->{'nombre'}'\n\n"; + } + } else { + $agent_id = get_agent_id($dbh,$agent_name); + exist_check($agent_id,'agent',$agent_name); + + my $module_exists = get_agent_module_id($dbh, $module_name, $agent_id); + non_exist_check($module_exists, 'module name', $module_name); + + print_log "[INFO] Adding module '$module_name' to agent '$agent_name'\n\n"; + } } else { $policy_id = enterprise_hook('get_policy_id',[$dbh, safe_input($policy_name)]); @@ -2222,7 +2491,11 @@ sub cli_create_plugin_module($) { if ($in_policy == 0) { $parameters{'nombre'} = safe_input($module_name); - $parameters{'id_agente'} = $agent_id; + + if (not defined $use_alias) { + $parameters{'id_agente'} = $agent_id; + } + $parameters{'ip_target'} = $module_address; } else { @@ -2299,7 +2572,14 @@ sub cli_create_plugin_module($) { $parameters{'warning_inverse'} = $warning_inverse unless !defined ($warning_inverse); if ($in_policy == 0) { - pandora_create_module_from_hash ($conf, \%parameters, $dbh); + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + $parameters{'id_agente'} = $id->{'id_agente'}; + pandora_create_module_from_hash ($conf, \%parameters, $dbh); + } + } else { + pandora_create_module_from_hash ($conf, \%parameters, $dbh); + } } else { enterprise_hook('pandora_create_policy_module_from_hash', [$conf, \%parameters, $dbh]); @@ -2312,16 +2592,36 @@ sub cli_create_plugin_module($) { ############################################################################## sub cli_delete_module() { - my ($module_name,$agent_name) = @ARGV[2..3]; + my ($module_name,$agent_name, $use_alias) = @ARGV[2..4]; - print_log "[INFO] Deleting module '$module_name' from agent '$agent_name' \n\n"; - - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); - my $id_module = get_agent_module_id($dbh,$module_name,$id_agent); - exist_check($id_module,'module',$module_name); - - pandora_delete_module($dbh,$id_module,$conf); + my @id_agents; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + my $id_agent; + + foreach my $id (@id_agents) { + print_log "[INFO] Deleting module '$module_name' from agent '$id->{'nombre'}' \n\n"; + + $id_agent = $id->{'id_agente'}; + exist_check($id_agent,'agent',$agent_name); + my $id_module = get_agent_module_id($dbh,$module_name,$id_agent); + if ($id_module == -1) { + next; + } + + pandora_delete_module($dbh,$id_module,$conf); + } + } else { + print_log "[INFO] Deleting module '$module_name' from agent '$agent_name' \n\n"; + + my $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + my $id_module = get_agent_module_id($dbh,$module_name,$id_agent); + exist_check($id_module,'module',$module_name); + + pandora_delete_module($dbh,$id_module,$conf); + } } ############################################################################## @@ -2370,18 +2670,41 @@ sub cli_delete_not_policy_modules() { ############################################################################## sub cli_create_template_module() { - my ($template_name,$module_name,$agent_name) = @ARGV[2..4]; + my ($template_name,$module_name,$agent_name, $use_alias) = @ARGV[2..5]; - print_log "[INFO] Adding template '$template_name' to module '$module_name' from agent '$agent_name' \n\n"; - - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); - my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); - exist_check($module_id,'module',$module_name); - my $template_id = get_template_id($dbh,$template_name); - exist_check($template_id,'template',$template_name); - - pandora_create_template_module ($conf, $dbh, $module_id, $template_id); + my @id_agents; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + print_log "[INFO] Adding template '$template_name' to module '$module_name' from agent '$agent_name' \n\n"; + + my $id_agent = $id->{'id_agente'}; + exist_check($id_agent,'agent',$agent_name); + my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); + if ($module_id == -1) { + print_log "[ERROR] Error: The module '$module_name' does not exist. \n\n"; + next; + } + + my $template_id = get_template_id($dbh,$template_name); + exist_check($template_id,'template',$template_name); + + pandora_create_template_module ($conf, $dbh, $module_id, $template_id); + } + } else { + print_log "[INFO] Adding template '$template_name' to module '$module_name' from agent '$agent_name' \n\n"; + + my $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); + exist_check($module_id,'module',$module_name); + my $template_id = get_template_id($dbh,$template_name); + exist_check($template_id,'template',$template_name); + + pandora_create_template_module ($conf, $dbh, $module_id, $template_id); + } } ############################################################################## @@ -2390,21 +2713,46 @@ sub cli_create_template_module() { ############################################################################## sub cli_delete_template_module() { - my ($template_name,$module_name,$agent_name) = @ARGV[2..4]; + my ($template_name,$module_name,$agent_name, $use_alias) = @ARGV[2..5]; - print_log "[INFO] Delete template '$template_name' from module '$module_name' from agent '$agent_name' \n\n"; + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$agent_name); - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); - my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); - exist_check($module_id,'module',$module_name); - my $template_id = get_template_id($dbh,$template_name); - exist_check($template_id,'template',$template_name); + my $id_agent; - my $template_module_id = get_template_module_id($dbh, $module_id, $template_id); - exist_check($template_module_id,"template '$template_name' on module",$module_name); + foreach my $id (@id_agents) { + print_log "[INFO] Delete template '$template_name' from module '$module_name' from agent '$agent_name' \n\n"; + + $id_agent = $id->{'id_agente'}; + exist_check($id_agent,'agent',$agent_name); + my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); + if ($module_id eq -1) { + print_log "[ERROR] Error: The module '$module_name' does not exist. \n\n"; + next; + } + my $template_id = get_template_id($dbh,$template_name); + exist_check($template_id,'template',$template_name); + + my $template_module_id = get_template_module_id($dbh, $module_id, $template_id); + exist_check($template_module_id,"template '$template_name' on module",$module_name); - pandora_delete_template_module ($dbh, $template_module_id); + pandora_delete_template_module ($dbh, $template_module_id); + } + } else { + print_log "[INFO] Delete template '$template_name' from module '$module_name' from agent '$agent_name' \n\n"; + + my $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); + exist_check($module_id,'module',$module_name); + my $template_id = get_template_id($dbh,$template_name); + exist_check($template_id,'template',$template_name); + + my $template_module_id = get_template_module_id($dbh, $module_id, $template_id); + exist_check($template_module_id,"template '$template_name' on module",$module_name); + + pandora_delete_template_module ($dbh, $template_module_id); + } } ############################################################################## @@ -2413,32 +2761,68 @@ sub cli_delete_template_module() { ############################################################################## sub cli_create_template_action() { - my ($action_name,$template_name,$module_name,$agent_name,$fires_min,$fires_max) = @ARGV[2..7]; + my ($action_name,$template_name,$module_name,$agent_name,$fires_min,$fires_max, $use_alias) = @ARGV[2..8]; - print_log "[INFO] Adding action '$action_name' to template '$template_name' in module '$module_name' from agent '$agent_name' with $fires_min min. fires and $fires_max max. fires\n\n"; - - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); - my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); - exist_check($module_id,'module',$module_name); - my $template_id = get_template_id($dbh,$template_name); - exist_check($template_id,'template',$template_name); - my $template_module_id = get_template_module_id($dbh,$module_id,$template_id); - exist_check($template_module_id,'template module',$template_name); - my $action_id = get_action_id($dbh,safe_input($action_name)); - exist_check($action_id,'action',$action_name); - - $fires_min = 0 unless defined ($fires_min); - $fires_max = 0 unless defined ($fires_max); - - my %parameters; - - $parameters{'id_alert_template_module'} = $template_module_id; - $parameters{'id_alert_action'} = $action_id; - $parameters{'fires_min'} = $fires_min; - $parameters{'fires_max'} = $fires_max; - - pandora_create_template_module_action ($conf, \%parameters, $dbh); + my @id_agents; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + print_log "[INFO] Adding action '$action_name' to template '$template_name' in module '$module_name' from agent '$agent_name' with $fires_min min. fires and $fires_max max. fires\n\n"; + + my $id_agent = $id->{'id_agente'}; + exist_check($id_agent,'agent',$agent_name); + my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); + if ($module_id eq -1) { + print_log "[ERROR] Error: The module '$module_name' does not exist. \n\n"; + next; + } + my $template_id = get_template_id($dbh,$template_name); + exist_check($template_id,'template',$template_name); + my $template_module_id = get_template_module_id($dbh,$module_id,$template_id); + exist_check($template_module_id,'template module',$template_name); + my $action_id = get_action_id($dbh,safe_input($action_name)); + exist_check($action_id,'action',$action_name); + + $fires_min = 0 unless defined ($fires_min); + $fires_max = 0 unless defined ($fires_max); + + my %parameters; + + $parameters{'id_alert_template_module'} = $template_module_id; + $parameters{'id_alert_action'} = $action_id; + $parameters{'fires_min'} = $fires_min; + $parameters{'fires_max'} = $fires_max; + + pandora_create_template_module_action ($conf, \%parameters, $dbh); + } + } else { + print_log "[INFO] Adding action '$action_name' to template '$template_name' in module '$module_name' from agent '$agent_name' with $fires_min min. fires and $fires_max max. fires\n\n"; + + my $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); + exist_check($module_id,'module',$module_name); + my $template_id = get_template_id($dbh,$template_name); + exist_check($template_id,'template',$template_name); + my $template_module_id = get_template_module_id($dbh,$module_id,$template_id); + exist_check($template_module_id,'template module',$template_name); + my $action_id = get_action_id($dbh,safe_input($action_name)); + exist_check($action_id,'action',$action_name); + + $fires_min = 0 unless defined ($fires_min); + $fires_max = 0 unless defined ($fires_max); + + my %parameters; + + $parameters{'id_alert_template_module'} = $template_module_id; + $parameters{'id_alert_action'} = $action_id; + $parameters{'fires_min'} = $fires_min; + $parameters{'fires_max'} = $fires_max; + + pandora_create_template_module_action ($conf, \%parameters, $dbh); + } } ############################################################################## @@ -2447,22 +2831,46 @@ sub cli_create_template_action() { ############################################################################## sub cli_delete_template_action() { - my ($action_name,$template_name,$module_name,$agent_name) = @ARGV[2..5]; + my ($action_name,$template_name,$module_name,$agent_name, $use_alias) = @ARGV[2..6]; - print_log "[INFO] Deleting action '$action_name' from template '$template_name' in module '$module_name' from agent '$agent_name')\n\n"; + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$agent_name); - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); - my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); - exist_check($module_id,'module',$module_name); - my $template_id = get_template_id($dbh,$template_name); - exist_check($template_id,'template',$template_name); - my $template_module_id = get_template_module_id($dbh,$module_id,$template_id); - exist_check($template_module_id,'template module',$template_name); - my $action_id = get_action_id($dbh,safe_input($action_name)); - exist_check($action_id,'action',$action_name); + foreach my $id (@id_agents) { + print_log "[INFO] Deleting action '$action_name' from template '$template_name' in module '$module_name' from agent '$agent_name')\n\n"; - pandora_delete_template_module_action ($dbh, $template_module_id, $action_id); + my $id_agent = $id->{'id_agente'}; + exist_check($id_agent,'agent',$agent_name); + my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); + if ($module_id eq -1) { + print_log "[ERROR] Error: The module '$module_name' does not exist. \n\n"; + next; + } + my $template_id = get_template_id($dbh,$template_name); + exist_check($template_id,'template',$template_name); + my $template_module_id = get_template_module_id($dbh,$module_id,$template_id); + exist_check($template_module_id,'template module',$template_name); + my $action_id = get_action_id($dbh,safe_input($action_name)); + exist_check($action_id,'action',$action_name); + + pandora_delete_template_module_action ($dbh, $template_module_id, $action_id); + } + } else { + print_log "[INFO] Deleting action '$action_name' from template '$template_name' in module '$module_name' from agent '$agent_name')\n\n"; + + my $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + my $module_id = get_agent_module_id($dbh,$module_name,$id_agent); + exist_check($module_id,'module',$module_name); + my $template_id = get_template_id($dbh,$template_name); + exist_check($template_id,'template',$template_name); + my $template_module_id = get_template_module_id($dbh,$module_id,$template_id); + exist_check($template_module_id,'template module',$template_name); + my $action_id = get_action_id($dbh,safe_input($action_name)); + exist_check($action_id,'action',$action_name); + + pandora_delete_template_module_action ($dbh, $template_module_id, $action_id); + } } ############################################################################## @@ -2471,9 +2879,11 @@ sub cli_delete_template_action() { ############################################################################## sub cli_data_module() { - my ($server_name,$agent_name,$module_name,$module_type,$module_new_data,$datetime) = @ARGV[2..7]; + my ($server_name,$agent_name,$module_name,$module_type,$module_new_data,$datetime,$use_alias) = @ARGV[2..8]; my $utimestamp; + my @id_agents; + if(defined($datetime)) { if ($datetime !~ /([0-9]{2,4})\-([0-1][0-9])\-([0-3][0-9]) +([0-2][0-9]):([0-5][0-9])/) { print_log "[ERROR] Invalid datetime $datetime. (Correct format: YYYY-MM-DD HH:mm)\n"; @@ -2490,29 +2900,58 @@ sub cli_data_module() { # The get_module_id has wrong name. Change in future my $module_type_id = get_module_id($dbh,$module_type); exist_check($module_type_id,'module type',$module_type); - - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); - - my $id_module = get_agent_module_id($dbh, $module_name, $id_agent); - exist_check($id_module, 'module name', $module_name); - + # Server_type 0 is dataserver my $server_id = get_server_id($dbh,$server_name,0); exist_check($server_id,'data server',$server_name); - - my $module = get_db_single_row ($dbh, 'SELECT * FROM tagente_modulo WHERE id_agente_modulo = ? AND id_tipo_modulo = ?', $id_module, $id_agent, $module_type_id); - - if(not defined($module->{'module_interval'})) { - print_log "[ERROR] No module found with this type. \n\n"; - exit; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + my $id_agent; + + foreach my $id (@id_agents) { + $id_agent = $id->{'id_agente'}; + exist_check($id_agent,'agent',$agent_name); + + my $id_module = get_agent_module_id($dbh, $module_name, $id_agent); + if ($id_module == -1) { + next; + } + + my $module = get_db_single_row ($dbh, 'SELECT * FROM tagente_modulo WHERE id_agente_modulo = ? AND id_tipo_modulo = ?', $id_module, $module_type_id); + + if(not defined($module->{'module_interval'})) { + print_log "[ERROR] No module found with this type. \n\n"; + exit; + } + + my %data = ('data' => $module_new_data); + + pandora_process_module ($conf, \%data, '', $module, $module_type, '', $utimestamp, $server_id, $dbh); + + print_log "[INFO] Inserting data to module '$module_name'\n\n"; + } + } else { + my $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + + my $id_module = get_agent_module_id($dbh, $module_name, $id_agent); + exist_check($id_module, 'module name', $module_name); + + my $module = get_db_single_row ($dbh, 'SELECT * FROM tagente_modulo WHERE id_agente_modulo = ? AND id_tipo_modulo = ?', $id_module, $module_type_id); + + if(not defined($module->{'module_interval'})) { + print_log "[ERROR] No module found with this type. \n\n"; + exit; + } + + my %data = ('data' => $module_new_data); + + pandora_process_module ($conf, \%data, '', $module, $module_type, '', $utimestamp, $server_id, $dbh); + + print_log "[INFO] Inserting data to module '$module_name'\n\n"; } - - my %data = ('data' => $module_new_data); - - pandora_process_module ($conf, \%data, '', $module, $module_type, '', $utimestamp, $server_id, $dbh); - - print_log "[INFO] Inserting data to module '$module_name'\n\n"; } ############################################################################## @@ -2578,10 +3017,20 @@ sub cli_user_update() { ############################################################################## sub cli_agent_update() { - my ($agent_name,$field,$new_value) = @ARGV[2..4]; - - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); + my ($agent_name,$field,$new_value,$use_alias) = @ARGV[2..5]; + + my @id_agents; + my $id_agent; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + foreach my $id (@id_agents) { + exist_check($id->{'id_agente'},'agent',$agent_name); + } + } else { + $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + } # agent_name, address, description, group_name, interval, os_name, disabled, parent_name, cascade_protection, icon_path, update_gis_data, custom_id @@ -2629,7 +3078,13 @@ sub cli_agent_update() { } # Add the address to the agent - add_new_address_agent ($dbh, $address_id, $id_agent); + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + add_new_address_agent ($dbh, $address_id, $id->{'id_agente'}); + } + } else { + add_new_address_agent ($dbh, $address_id, $id_agent); + } $field = 'direccion'; } @@ -2637,14 +3092,24 @@ sub cli_agent_update() { print_log "[ERROR] Field '$field' doesnt exist\n\n"; exit; } - - print_log "[INFO] Updating field '$field' in agent '$agent_name'\n\n"; + + if (defined $use_alias and $use_alias eq 'use_alias') { + print_log "[INFO] Updating field '$field' in agents with alias '$agent_name'\n\n"; + } else { + print_log "[INFO] Updating field '$field' in agent '$agent_name'\n\n"; + } my $update; $update->{$field} = $new_value; - pandora_update_table_from_hash ($conf, $update, 'id_agente', safe_input($id_agent), 'tagente', $dbh); + if (defined $use_alias and $use_alias eq 'use_alias') { + foreach my $id (@id_agents) { + pandora_update_table_from_hash ($conf, $update, 'id_agente', safe_input($id->{'id_agente'}), 'tagente', $dbh); + } + } else { + pandora_update_table_from_hash ($conf, $update, 'id_agente', safe_input($id_agent), 'tagente', $dbh); + } } ############################################################################## @@ -2901,150 +3366,306 @@ sub pandora_check_plugin_module_fields($) { ############################################################################## sub cli_module_update() { - my ($module_name,$agent_name,$field,$new_value) = @ARGV[2..5]; - - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); - my $id_agent_module = get_agent_module_id ($dbh, $module_name, $id_agent); - exist_check($id_agent_module,'agent module',$module_name); - - # Check and adjust parameters in common values - - if($field eq 'min' || $field eq 'max' || $field eq 'post_process' || $field eq 'history_data') { - # Fields admited, no changes - } - elsif($field eq 'interval') { - $field = 'module_interval'; - } - elsif($field eq 'warning_min') { - $field = 'min_warning'; - } - elsif($field eq 'warning_max') { - $field = 'max_warning'; - } - elsif($field eq 'critical_min') { - $field = 'min_critical'; - } - elsif($field eq 'critical_max') { - $field = 'max_critical'; - } - elsif($field eq 'warning_str') { - $field = 'str_warning'; - $new_value = safe_input($new_value); - } - elsif($field eq 'critical_str') { - $field = 'str_critical'; - $new_value = safe_input($new_value); - } - elsif($field eq 'agent_name') { - my $id_agent_change = get_agent_id($dbh,$new_value); - exist_check($id_agent_change,'agent',$new_value); - my $id_agent_module_exist = get_agent_module_id ($dbh, $module_name, $id_agent_change); - if($id_agent_module_exist != -1) { - print_log "[ERROR] A module called '$module_name' already exist in the agent '$new_value'\n\n"; - exit; - } - $field = 'id_agente'; - $new_value = $id_agent_change; - } - elsif ($field eq 'module_name') { - my $id_agent_module_change = get_agent_module_id ($dbh, $new_value, $id_agent); - if ($id_agent_module_change != -1) { - print_log "[ERROR] A module called '$new_value' already exist in the agent '$agent_name'\n\n"; - exit; - } - $field = 'nombre'; - $new_value = safe_input($new_value); - } - elsif ($field eq 'description') { - $field = 'descripcion'; - $new_value = safe_input($new_value); - } - elsif ($field eq 'module_group') { - my $module_group_id = get_module_group_id($dbh,$new_value); - - if ($module_group_id == -1) { - print_log "[ERROR] Module group '$new_value' doesnt exist\n\n"; - exit; - } - $field = 'id_module_group'; - $new_value = $module_group_id; - } - elsif ($field eq 'enable_unknown_events') { - my $disabled_types_event = {}; - if ($new_value) { - $disabled_types_event->{'going_unknown'} = 0; - } - else { - $disabled_types_event->{'going_unknown'} = 1; - } - $field = 'disabled_types_event'; - $new_value = encode_json($disabled_types_event); - } - elsif ($field eq 'ff_threshold') { - $field = 'min_ff_event'; - } - elsif ($field eq 'each_ff') { - $field = 'each_ff'; - } - elsif ($field eq 'ff_threshold_normal') { - $field = 'min_ff_event_normal'; - } - elsif ($field eq 'ff_threshold_warning') { - $field = 'min_ff_event_warning'; - } - elsif ($field eq 'ff_threshold_critical') { - $field = 'min_ff_event_critical'; - } - elsif ($field eq 'critical_instructions') { - $field = 'critical_instructions'; - } - elsif ($field eq 'warning_instructions') { - $field = 'warning_instructions'; - } - elsif ($field eq 'unknown_instructions') { - $field = 'unknown_instructions'; - } - else { - # If is not a common value, check type and call type update funtion - my $type = pandora_get_module_type($dbh,$id_agent_module); - - my %field_value; - $field_value{'field'} = $field; - $field_value{'new_value'} = $new_value; - - if($type eq 'data') { - pandora_check_data_module_fields(\%field_value); - } - elsif($type eq 'network') { - pandora_check_network_module_fields(\%field_value); - } - elsif($type eq 'snmp') { - pandora_check_snmp_module_fields(\%field_value); - } - elsif($type eq 'plugin') { - pandora_check_plugin_module_fields(\%field_value); - } - else { - print_log "[ERROR] The field '$field' is not available for this type of module\n\n"; - } - - $field = $field_value{'field'}; - $new_value = $field_value{'new_value'}; - } - - print_log "[INFO] Updating field '$field' in module '$module_name' of agent '$agent_name' with new value '$new_value'\n\n"; - - my $update; - - $update->{$field} = $new_value; + my ($module_name,$agent_name,$field,$new_value, $use_alias) = @ARGV[2..6]; - my $policy_id = enterprise_hook('get_id_policy_module_agent_module',[$dbh, safe_input($id_agent_module)]); - if ( $policy_id > 0) { - $update->{policy_linked} = 0; + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + my $save_initial_field = $field; + my $save_new_value = $new_value; + + foreach my $id (@id_agents) { + $field = $save_initial_field; + $new_value = $save_new_value; + my $id_agent = $id->{'id_agente'}; + exist_check($id_agent,'agent',$agent_name); + my $id_agent_module = get_agent_module_id ($dbh, $module_name, $id_agent); + if ($id_agent_module == -1) { + next; + } + + # Check and adjust parameters in common values + + if($field eq 'min' || $field eq 'max' || $field eq 'post_process' || $field eq 'history_data') { + # Fields admited, no changes + } + elsif($field eq 'interval') { + $field = 'module_interval'; + } + elsif($field eq 'warning_min') { + $field = 'min_warning'; + } + elsif($field eq 'warning_max') { + $field = 'max_warning'; + } + elsif($field eq 'critical_min') { + $field = 'min_critical'; + } + elsif($field eq 'critical_max') { + $field = 'max_critical'; + } + elsif($field eq 'warning_str') { + $field = 'str_warning'; + $new_value = safe_input($new_value); + } + elsif($field eq 'critical_str') { + $field = 'str_critical'; + $new_value = safe_input($new_value); + } + elsif($field eq 'agent_name') { + my $id_agent_change = get_agent_id($dbh,$new_value); + exist_check($id_agent_change,'agent',$new_value); + my $id_agent_module_exist = get_agent_module_id ($dbh, $module_name, $id_agent_change); + if($id_agent_module_exist != -1) { + print_log "[ERROR] A module called '$module_name' already exist in the agent '$new_value'\n\n"; + exit; + } + $field = 'id_agente'; + $new_value = $id_agent_change; + } + elsif ($field eq 'module_name') { + my $id_agent_module_change = get_agent_module_id ($dbh, $new_value, $id_agent); + if ($id_agent_module_change != -1) { + print_log "[ERROR] A module called '$new_value' already exist in the agent '$agent_name'\n\n"; + exit; + } + $field = 'nombre'; + $new_value = safe_input($new_value); + } + elsif ($field eq 'description') { + $field = 'descripcion'; + $new_value = safe_input($new_value); + } + elsif ($field eq 'module_group') { + my $module_group_id = get_module_group_id($dbh,$new_value); + + if ($module_group_id == -1) { + print_log "[ERROR] Module group '$new_value' doesnt exist\n\n"; + exit; + } + $field = 'id_module_group'; + $new_value = $module_group_id; + } + elsif ($field eq 'enable_unknown_events') { + my $disabled_types_event = {}; + if ($new_value) { + $disabled_types_event->{'going_unknown'} = 0; + } + else { + $disabled_types_event->{'going_unknown'} = 1; + } + $field = 'disabled_types_event'; + $new_value = encode_json($disabled_types_event); + } + elsif ($field eq 'ff_threshold') { + $field = 'min_ff_event'; + } + elsif ($field eq 'each_ff') { + $field = 'each_ff'; + } + elsif ($field eq 'ff_threshold_normal') { + $field = 'min_ff_event_normal'; + } + elsif ($field eq 'ff_threshold_warning') { + $field = 'min_ff_event_warning'; + } + elsif ($field eq 'ff_threshold_critical') { + $field = 'min_ff_event_critical'; + } + elsif ($field eq 'critical_instructions') { + $field = 'critical_instructions'; + } + elsif ($field eq 'warning_instructions') { + $field = 'warning_instructions'; + } + elsif ($field eq 'unknown_instructions') { + $field = 'unknown_instructions'; + } + else { + # If is not a common value, check type and call type update funtion + my $type = pandora_get_module_type($dbh,$id_agent_module); + print("TYPE EN ELSE".$type); + my %field_value; + $field_value{'field'} = $field; + $field_value{'new_value'} = $new_value; + + if($type eq 'data') { + pandora_check_data_module_fields(\%field_value); + } + elsif($type eq 'network') { + pandora_check_network_module_fields(\%field_value); + } + elsif($type eq 'snmp') { + pandora_check_snmp_module_fields(\%field_value); + } + elsif($type eq 'plugin') { + pandora_check_plugin_module_fields(\%field_value); + } + else { + print_log "[ERROR] The field '$field' is not available for this type of module\n\n"; + } + + $field = $field_value{'field'}; + $new_value = $field_value{'new_value'}; + } + + print_log "[INFO] Updating field '$field' in module '$module_name' of agent '$agent_name' with new value '$new_value'\n\n"; + + my $update; + + $update->{$field} = $new_value; + + my $policy_id = enterprise_hook('get_id_policy_module_agent_module',[$dbh, safe_input($id_agent_module)]); + if ( $policy_id > 0) { + $update->{policy_linked} = 0; + } + + pandora_update_module_from_hash ($conf, $update, 'id_agente_modulo', $id_agent_module, $dbh); + } + } else { + my $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + my $id_agent_module = get_agent_module_id ($dbh, $module_name, $id_agent); + exist_check($id_agent_module,'agent module',$module_name); + + # Check and adjust parameters in common values + + if($field eq 'min' || $field eq 'max' || $field eq 'post_process' || $field eq 'history_data') { + # Fields admited, no changes + } + elsif($field eq 'interval') { + $field = 'module_interval'; + } + elsif($field eq 'warning_min') { + $field = 'min_warning'; + } + elsif($field eq 'warning_max') { + $field = 'max_warning'; + } + elsif($field eq 'critical_min') { + $field = 'min_critical'; + } + elsif($field eq 'critical_max') { + $field = 'max_critical'; + } + elsif($field eq 'warning_str') { + $field = 'str_warning'; + $new_value = safe_input($new_value); + } + elsif($field eq 'critical_str') { + $field = 'str_critical'; + $new_value = safe_input($new_value); + } + elsif($field eq 'agent_name') { + my $id_agent_change = get_agent_id($dbh,$new_value); + exist_check($id_agent_change,'agent',$new_value); + my $id_agent_module_exist = get_agent_module_id ($dbh, $module_name, $id_agent_change); + if($id_agent_module_exist != -1) { + print_log "[ERROR] A module called '$module_name' already exist in the agent '$new_value'\n\n"; + exit; + } + $field = 'id_agente'; + $new_value = $id_agent_change; + } + elsif ($field eq 'module_name') { + my $id_agent_module_change = get_agent_module_id ($dbh, $new_value, $id_agent); + if ($id_agent_module_change != -1) { + print_log "[ERROR] A module called '$new_value' already exist in the agent '$agent_name'\n\n"; + exit; + } + $field = 'nombre'; + $new_value = safe_input($new_value); + } + elsif ($field eq 'description') { + $field = 'descripcion'; + $new_value = safe_input($new_value); + } + elsif ($field eq 'module_group') { + my $module_group_id = get_module_group_id($dbh,$new_value); + + if ($module_group_id == -1) { + print_log "[ERROR] Module group '$new_value' doesnt exist\n\n"; + exit; + } + $field = 'id_module_group'; + $new_value = $module_group_id; + } + elsif ($field eq 'enable_unknown_events') { + my $disabled_types_event = {}; + if ($new_value) { + $disabled_types_event->{'going_unknown'} = 0; + } + else { + $disabled_types_event->{'going_unknown'} = 1; + } + $field = 'disabled_types_event'; + $new_value = encode_json($disabled_types_event); + } + elsif ($field eq 'ff_threshold') { + $field = 'min_ff_event'; + } + elsif ($field eq 'each_ff') { + $field = 'each_ff'; + } + elsif ($field eq 'ff_threshold_normal') { + $field = 'min_ff_event_normal'; + } + elsif ($field eq 'ff_threshold_warning') { + $field = 'min_ff_event_warning'; + } + elsif ($field eq 'ff_threshold_critical') { + $field = 'min_ff_event_critical'; + } + elsif ($field eq 'critical_instructions') { + $field = 'critical_instructions'; + } + elsif ($field eq 'warning_instructions') { + $field = 'warning_instructions'; + } + elsif ($field eq 'unknown_instructions') { + $field = 'unknown_instructions'; + } + else { + # If is not a common value, check type and call type update funtion + my $type = pandora_get_module_type($dbh,$id_agent_module); + + my %field_value; + $field_value{'field'} = $field; + $field_value{'new_value'} = $new_value; + + if($type eq 'data') { + pandora_check_data_module_fields(\%field_value); + } + elsif($type eq 'network') { + pandora_check_network_module_fields(\%field_value); + } + elsif($type eq 'snmp') { + pandora_check_snmp_module_fields(\%field_value); + } + elsif($type eq 'plugin') { + pandora_check_plugin_module_fields(\%field_value); + } + else { + print_log "[ERROR] The field '$field' is not available for this type of module\n\n"; + } + + $field = $field_value{'field'}; + $new_value = $field_value{'new_value'}; + } + + print_log "[INFO] Updating field '$field' in module '$module_name' of agent '$agent_name' with new value '$new_value'\n\n"; + + my $update; + + $update->{$field} = $new_value; + + my $policy_id = enterprise_hook('get_id_policy_module_agent_module',[$dbh, safe_input($id_agent_module)]); + if ( $policy_id > 0) { + $update->{policy_linked} = 0; + } + + pandora_update_module_from_hash ($conf, $update, 'id_agente_modulo', $id_agent_module, $dbh); } - - pandora_update_module_from_hash ($conf, $update, 'id_agente_modulo', $id_agent_module, $dbh); } ############################################################################## @@ -3401,7 +4022,7 @@ sub cli_delete_profile() { ############################################################################## sub cli_create_event() { - my ($event,$event_type,$group_name,$agent_name,$module_name,$event_status,$severity,$template_name, $user_name, $comment, $source, $id_extra, $tags, $custom_data,$force_create_agent,$c_instructions,$w_instructions,$u_instructions) = @ARGV[2..19]; + my ($event,$event_type,$group_name,$agent_name,$module_name,$event_status,$severity,$template_name, $user_name, $comment, $source, $id_extra, $tags, $custom_data,$force_create_agent,$c_instructions,$w_instructions,$u_instructions, $use_alias) = @ARGV[2..20]; $event_status = 0 unless defined($event_status); $severity = 0 unless defined($severity); @@ -3427,58 +4048,108 @@ sub cli_create_event() { } my $id_agent; - - if (! $agent_name) { - $id_agent = 0; - } - else { - $id_agent = get_agent_id($dbh,$agent_name); - # exist_check($id_agent,'agent',$agent_name); - if($id_agent == -1){ - if($force_create_agent == 1){ - pandora_create_agent ($conf, '', $agent_name, '', '', '', '', 'Created by cli_create_event', '', $dbh); - print_log "[INFO] Adding agent '$agent_name' \n\n"; - $id_agent = get_agent_id($dbh,$agent_name); + + if (defined $use_alias and $use_alias eq 'use_alias') { + + my @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + if (! $agent_name) { + $id_agent = 0; } - else{ - exist_check($id_agent,'agent',$agent_name); + else { + $id_agent = $id->{'id_agente'}; } + + my $id_agentmodule; + + if (! $module_name) { + $id_agentmodule = 0; + } + else { + $id_agentmodule = get_agent_module_id($dbh,$module_name,$id_agent); + if ($id_agentmodule eq -1) { + next; + } + } + + my $id_alert_agent_module; + + if(defined($template_name) && $template_name ne '') { + my $id_template = get_template_id($dbh,$template_name); + exist_check($id_template,'template',$template_name); + $id_alert_agent_module = get_template_module_id($dbh,$id_agentmodule,$id_template); + exist_check($id_alert_agent_module,'alert template module',$template_name); + } + else { + $id_alert_agent_module = 0; + } + + if (defined($comment) && $comment ne '') { + $comment = '<b>-- Added comment by '.$user_name. ' ['. localtime(time).'] --</b><br>'.$comment.'<br>'; + } + print_log "[INFO] Adding event '$event' for agent '$agent_name' \n\n"; + + # Base64 encode custom data + $custom_data = encode_base64 ($custom_data); + + pandora_event ($conf, $event, $id_group, $id_agent, $severity, + $id_alert_agent_module, $id_agentmodule, $event_type, $event_status, $dbh, $source, $user_name, $comment, $id_extra, $tags, $c_instructions, $w_instructions, $u_instructions, $custom_data); } + } else { + if (! $agent_name) { + $id_agent = 0; + } + else { + $id_agent = get_agent_id($dbh,$agent_name); + # exist_check($id_agent,'agent',$agent_name); + if($id_agent == -1){ + if($force_create_agent == 1){ + pandora_create_agent ($conf, '', $agent_name, '', '', '', '', 'Created by cli_create_event', '', $dbh); + print_log "[INFO] Adding agent '$agent_name' \n\n"; + $id_agent = get_agent_id($dbh,$agent_name); + } + else{ + exist_check($id_agent,'agent',$agent_name); + } + } + + } + + my $id_agentmodule; + + if (! $module_name) { + $id_agentmodule = 0; + } + else { + $id_agentmodule = get_agent_module_id($dbh,$module_name,$id_agent); + exist_check($id_agentmodule,'module',$module_name); + } + + my $id_alert_agent_module; + + if(defined($template_name) && $template_name ne '') { + my $id_template = get_template_id($dbh,$template_name); + exist_check($id_template,'template',$template_name); + $id_alert_agent_module = get_template_module_id($dbh,$id_agentmodule,$id_template); + exist_check($id_alert_agent_module,'alert template module',$template_name); + } + else { + $id_alert_agent_module = 0; + } + + if (defined($comment) && $comment ne '') { + $comment = '<b>-- Added comment by '.$user_name. ' ['. localtime(time).'] --</b><br>'.$comment.'<br>'; + } + print_log "[INFO] Adding event '$event' for agent '$agent_name' \n\n"; + + # Base64 encode custom data + $custom_data = encode_base64 ($custom_data); + + pandora_event ($conf, $event, $id_group, $id_agent, $severity, + $id_alert_agent_module, $id_agentmodule, $event_type, $event_status, $dbh, $source, $user_name, $comment, $id_extra, $tags, $c_instructions, $w_instructions, $u_instructions, $custom_data); } - - my $id_agentmodule; - - if (! $module_name) { - $id_agentmodule = 0; - } - else { - $id_agentmodule = get_agent_module_id($dbh,$module_name,$id_agent); - exist_check($id_agentmodule,'module',$module_name); - } - - my $id_alert_agent_module; - - if(defined($template_name) && $template_name ne '') { - my $id_template = get_template_id($dbh,$template_name); - exist_check($id_template,'template',$template_name); - $id_alert_agent_module = get_template_module_id($dbh,$id_agentmodule,$id_template); - exist_check($id_alert_agent_module,'alert template module',$template_name); - } - else { - $id_alert_agent_module = 0; - } - - if (defined($comment) && $comment ne '') { - $comment = '<b>-- Added comment by '.$user_name. ' ['. localtime(time).'] --</b><br>'.$comment.'<br>'; - } - print_log "[INFO] Adding event '$event' for agent '$agent_name' \n\n"; - - # Base64 encode custom data - $custom_data = encode_base64 ($custom_data); - - pandora_event ($conf, $event, $id_group, $id_agent, $severity, - $id_alert_agent_module, $id_agentmodule, $event_type, $event_status, $dbh, $source, $user_name, $comment, $id_extra, $tags, $c_instructions, $w_instructions, $u_instructions, $custom_data); } ############################################################################## @@ -3487,20 +4158,10 @@ sub cli_create_event() { ############################################################################## sub cli_validate_event() { - my ($agent_name, $module_name, $datetime_min, $datetime_max, $user_name, $criticity, $template_name) = @ARGV[2..8]; + my ($agent_name, $module_name, $datetime_min, $datetime_max, $user_name, $criticity, $template_name, $use_alias) = @ARGV[2..9]; my $id_agent = ''; my $id_agentmodule = ''; - if(defined($agent_name) && $agent_name ne '') { - $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); - - if($module_name ne '') { - $id_agentmodule = get_agent_module_id($dbh, $module_name, $id_agent); - exist_check($id_agentmodule,'module',$module_name); - } - } - if(defined($datetime_min) && $datetime_min ne '') { if ($datetime_min !~ /([0-9]{2,4})\-([0-1][0-9])\-([0-3][0-9]) +([0-2][0-9]):([0-5][0-9])/) { print_log "[ERROR] Invalid datetime_min format. (Correct format: YYYY-MM-DD HH:mm)\n"; @@ -3519,17 +4180,57 @@ sub cli_validate_event() { $datetime_max .= ":00"; } - my $id_alert_agent_module = ''; - - if(defined($template_name) && $template_name ne '') { - my $id_template = get_template_id($dbh,$template_name); - exist_check($id_template,'template',$template_name); - $id_alert_agent_module = get_template_module_id($dbh,$id_agentmodule,$id_template); - exist_check($id_alert_agent_module,'template module',$template_name); - } + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + if(defined($agent_name) && $agent_name ne '') { + $id_agent = $id->{'id_agente'}; + exist_check($id_agent,'agent',$agent_name); - pandora_validate_event_filter ($conf, $id_agentmodule, $id_agent, $datetime_min, $datetime_max, $user_name, $id_alert_agent_module, $criticity, $dbh); - print_log "[INFO] Validating event for agent '$agent_name'\n\n"; + if($module_name ne '') { + $id_agentmodule = get_agent_module_id($dbh, $module_name, $id_agent); + if ($id_agentmodule eq -1) { + next; + } + } + } + + my $id_alert_agent_module = ''; + + if(defined($template_name) && $template_name ne '') { + my $id_template = get_template_id($dbh,$template_name); + exist_check($id_template,'template',$template_name); + $id_alert_agent_module = get_template_module_id($dbh,$id_agentmodule,$id_template); + exist_check($id_alert_agent_module,'template module',$template_name); + } + + pandora_validate_event_filter ($conf, $id_agentmodule, $id_agent, $datetime_min, $datetime_max, $user_name, $id_alert_agent_module, $criticity, $dbh); + print_log "[INFO] Validating event for agent '$id->{'nombre'}'\n\n"; + } + } else { + if(defined($agent_name) && $agent_name ne '') { + $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + + if($module_name ne '') { + $id_agentmodule = get_agent_module_id($dbh, $module_name, $id_agent); + exist_check($id_agentmodule,'module',$module_name); + } + } + + my $id_alert_agent_module = ''; + + if(defined($template_name) && $template_name ne '') { + my $id_template = get_template_id($dbh,$template_name); + exist_check($id_template,'template',$template_name); + $id_alert_agent_module = get_template_module_id($dbh,$id_agentmodule,$id_template); + exist_check($id_alert_agent_module,'template module',$template_name); + } + + pandora_validate_event_filter ($conf, $id_agentmodule, $id_agent, $datetime_min, $datetime_max, $user_name, $id_alert_agent_module, $criticity, $dbh); + print_log "[INFO] Validating event for agent '$agent_name'\n\n"; + } } ############################################################################## @@ -3675,38 +4376,84 @@ sub cli_create_incident() { sub cli_delete_data($) { my $ltotal = shift; - my ($opt, $name, $name2) = @ARGV[2..4]; + my ($opt, $name, $name2, $use_alias) = @ARGV[2..5]; + if($opt eq '-m' || $opt eq '--m') { - # Delete module data - param_check($ltotal, 3) unless ($name2 ne ''); - my $id_agent = get_agent_id($dbh,$name2); - exist_check($id_agent,'agent',$name2); + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$name2); + + foreach my $id (@id_agents) { + # Delete module data + param_check($ltotal, 3) unless ($name2 ne ''); + my $id_agent = $id->{'id_agente'}; + exist_check($id_agent,'agent',$name2); + + my $id_module = get_agent_module_id($dbh,$name,$id_agent); + exist_check($id_module,'module',$name); + + print_log "DELETING THE DATA OF THE MODULE $name OF THE AGENT $name2\n\n"; + + pandora_delete_data($dbh, 'module', $id_module); + } + } else { + # Delete module data + param_check($ltotal, 3) unless ($name2 ne ''); + my $id_agent = get_agent_id($dbh,$name2); + exist_check($id_agent,'agent',$name2); + + my $id_module = get_agent_module_id($dbh,$name,$id_agent); + exist_check($id_module,'module',$name); - my $id_module = get_agent_module_id($dbh,$name,$id_agent); - exist_check($id_module,'module',$name); - - print_log "DELETING THE DATA OF THE MODULE $name OF THE AGENT $name2\n\n"; - - pandora_delete_data($dbh, 'module', $id_module); + print_log "DELETING THE DATA OF THE MODULE $name OF THE AGENT $name2\n\n"; + + pandora_delete_data($dbh, 'module', $id_module); + } + } elsif($opt eq '-a' || $opt eq '--a') { - # Delete agent's modules data - my $id_agent = get_agent_id($dbh,$name); - exist_check($id_agent,'agent',$name); + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$name); + foreach my $id (@id_agents) { + # Delete agent's modules data + my $id_agent = $id->{'id_agente'}; + exist_check($id_agent,'agent',$name); - print_log "DELETING THE DATA OF THE AGENT $name\n\n"; + print_log "DELETING THE DATA OF THE AGENT $name\n\n"; - pandora_delete_data($dbh, 'module', $id_agent); + pandora_delete_data($dbh, 'module', $id_agent); + } + } else { + my $id_agent = get_agent_id($dbh,$name); + exist_check($id_agent,'agent',$name); + + print_log "DELETING THE DATA OF THE AGENT $name\n\n"; + + pandora_delete_data($dbh, 'module', $id_agent); + } } elsif($opt eq '-g' || $opt eq '--g') { - # Delete group's modules data - my $id_group = get_group_id($dbh,$name); - exist_check($id_group,'group',$name); - - print_log "DELETING THE DATA OF THE GROUP $name\n\n"; - - pandora_delete_data($dbh, 'group', $id_group); + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$name); + + foreach my $id (@id_agents) { + # Delete group's modules data + my $id_group = $id->{'id_agente'}; + exist_check($id_group,'group',$name); + + print_log "DELETING THE DATA OF THE GROUP $name\n\n"; + + pandora_delete_data($dbh, 'group', $id_group); + } + } else { + # Delete group's modules data + my $id_group = get_group_id($dbh,$name); + exist_check($id_group,'group',$name); + + print_log "DELETING THE DATA OF THE GROUP $name\n\n"; + + pandora_delete_data($dbh, 'group', $id_group); + } } else { print_log "[ERROR] Invalid parameter '$opt'.\n\n"; @@ -3863,21 +4610,20 @@ sub cli_get_module_id() { ############################################################################## -# Show the group name where is a given agent +# Show the group name where a given agent is # Related option: --get_agent_group ############################################################################## sub cli_get_agent_group() { - my $agent_name = @ARGV[2]; - + my ($agent_name,$use_alias) = @ARGV[2..3]; + if (is_metaconsole($conf) == 1) { my $agents_groups = enterprise_hook('get_metaconsole_agent',[$dbh, $agent_name]); - if (scalar(@{$agents_groups}) != 0) { + if (not defined $use_alias and scalar(@{$agents_groups}) != 0) { foreach my $agent (@{$agents_groups}) { my @test = $agent; - print Dumper $test[0]; my $group_name = get_group_name ($dbh, $agent->{'id_grupo'}); print "Server: $agent->{'server_name'} Agent: $agent->{'nombre'} Name Group: $group_name \n\n"; } @@ -3890,28 +4636,68 @@ sub cli_get_agent_group() { foreach my $server (@servers_id) { my $dbh_metaconsole = enterprise_hook('get_node_dbh',[$conf, $server, $dbh]); - my $id_agent = get_agent_id($dbh_metaconsole,$agent_name); - - if ($id_agent == -1) { - next; - } - else { - my $id_group = get_agent_group ($dbh_metaconsole, $id_agent); - my $group_name = get_group_name ($dbh_metaconsole, $id_group); - $agent_name = safe_output($agent_name); - print "[INFO] Agent: $agent_name Name Group: $group_name\n\n"; + my @id_agents; + my $id_agent; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh_metaconsole,$agent_name); + + foreach my $id (@id_agents) { + + if ($id->{'id_agente'} == -1) { + next; + } + else { + my $id_group = get_agent_group ($dbh_metaconsole, $id->{'id_agente'}); + my $group_name = get_group_name ($dbh_metaconsole, $id_group); + $agent_name = safe_output($agent_name); + print "[INFO] Agent: $id->{'nombre'} Name Group: $group_name\n\n"; + } + } + } else { + $id_agent = get_agent_id($dbh_metaconsole,$agent_name); + + if ($id_agent == -1) { + next; + } + else { + my $id_group = get_agent_group ($dbh_metaconsole, $id_agent); + my $group_name = get_group_name ($dbh_metaconsole, $id_group); + $agent_name = safe_output($agent_name); + print "[INFO] Agent: $agent_name Name Group: $group_name\n\n"; + } } } } } else { - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); + my @id_agents; + my $id_agent; + my $id_group; + my $group_name; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + exist_check($id->{'id_agente'},'agent',$agent_name); + + $id_group = get_agent_group ($dbh, $id->{'id_agente'}); - my $id_group = get_agent_group ($dbh, $id_agent); + $group_name = get_group_name ($dbh, $id_group); + print $group_name."\n"; + } + } else { + $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + + $id_group = get_agent_group ($dbh, $id_agent); - my $group_name = get_group_name ($dbh, $id_group); - print $group_name; + $group_name = get_group_name ($dbh, $id_group); + print $group_name; + } + + } } @@ -3920,12 +4706,13 @@ sub cli_get_agent_group() { # Related option: --get_agent_group_id ############################################################################## sub cli_get_agent_group_id() { - my $agent_name = @ARGV[2]; + my ($agent_name,$use_alias) = @ARGV[2..3]; if (is_metaconsole($conf) == 1) { + my $agents_groups = enterprise_hook('get_metaconsole_agent',[$dbh, $agent_name]); - if (scalar(@{$agents_groups}) != 0) { + if (not defined $use_alias and scalar(@{$agents_groups}) != 0) { foreach my $agent (@{$agents_groups}) { print "Server: $agent->{'server_name'} Agent: $agent->{'nombre'} ID Group: $agent->{'id_grupo'}\n\n"; @@ -3939,26 +4726,62 @@ sub cli_get_agent_group_id() { foreach my $server (@servers_id) { my $dbh_metaconsole = enterprise_hook('get_node_dbh',[$conf, $server, $dbh]); - my $id_agent = get_agent_id($dbh_metaconsole,$agent_name); - - if ($id_agent == -1) { - next; - } - else { - my $id_group = get_agent_group ($dbh_metaconsole, $id_agent); - $agent_name = safe_output($agent_name); - print "Agent: $agent_name ID Group: $id_group\n\n"; + my @id_agents; + my $id_agent; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh_metaconsole,$agent_name); + + foreach my $id (@id_agents) { + + if ($id->{'id_agente'} == -1) { + next; + } + else { + my $id_group = get_agent_group ($dbh_metaconsole, $id->{'id_agente'}); + $agent_name = safe_output($agent_name); + print "Agent: $id->{'nombre'} ID Group: $id_group\n\n"; + } + } + } else { + $id_agent = get_agent_id($dbh_metaconsole,$agent_name); + + if ($id_agent == -1) { + next; + } + else { + my $id_group = get_agent_group ($dbh_metaconsole, $id_agent); + $agent_name = safe_output($agent_name); + print "Agent: $agent_name ID Group: $id_group\n\n"; + } } } } } else { - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); - - my $id_group = get_agent_group ($dbh, $id_agent); + my @id_agents; + my $id_agent; + my $id_group; + my $group_name; - print $id_group; + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + exist_check($id->{'id_agente'},'agent',$agent_name); + + $id_group = get_agent_group ($dbh, $id->{'id_agente'}); + + print $id_group."\n"; + } + } else { + $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + + $id_group = get_agent_group ($dbh, $id_agent); + + print $id_group; + } } } @@ -3986,20 +4809,43 @@ sub cli_get_agents_module_current_data() { ############################################################################## sub cli_get_agent_modules() { - my $agent_name = @ARGV[2]; + my ($agent_name,$use_alias) = @ARGV[2..3]; - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); + my @id_agents; + my $id_agent; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + exist_check($id->{'id_agente'},'agent',$agent_name); + + my $modules = pandora_get_agent_modules ($dbh, $id->{'id_agente'}); + + if(scalar(@{$modules}) == 0) { + print_log "[INFO] The agent '$agent_name' have no modules\n\n"; + } + + print "\n".$id->{'nombre'}."\n"; + print "id_module, module_name\n"; + foreach my $module (@{$modules}) { + print $module->{'id_agente_modulo'}.",".safe_output($module->{'nombre'})."\n"; + } + } + } else { + $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); - my $modules = pandora_get_agent_modules ($dbh, $id_agent); + my $modules = pandora_get_agent_modules ($dbh, $id_agent); + + if(scalar(@{$modules}) == 0) { + print_log "[INFO] The agent '$agent_name' have no modules\n\n"; + } - if(scalar(@{$modules}) == 0) { - print_log "[INFO] The agent '$agent_name' have not modules\n\n"; - } - - print "id_module, module_name\n"; - foreach my $module (@{$modules}) { - print $module->{'id_agente_modulo'}.",".safe_output($module->{'nombre'})."\n"; + print "id_module, module_name\n"; + foreach my $module (@{$modules}) { + print $module->{'id_agente_modulo'}.",".safe_output($module->{'nombre'})."\n"; + } } } @@ -4008,7 +4854,15 @@ sub cli_create_synthetic() { my $synthetic_type = @ARGV[3]; my $agent_name = @ARGV[4]; - my @module_data = @ARGV[5..$#ARGV]; + + my @module_data; + + if (@ARGV[$#ARGV] == "use_alias") { + @module_data = @ARGV[5..$#ARGV-1]; + } else { + @module_data = @ARGV[5..$#ARGV]; + } + my $module; my (@filterdata,@data_module); @@ -4030,86 +4884,181 @@ sub cli_create_synthetic() { $module->{'prediction_module'} = 3; # Synthetic code is 3 $module->{'flag'} = 1; - my $id_agent = int(get_agent_id($dbh,$agent_name)); - - if ($id_agent > 0) { - foreach my $i (0 .. $#module_data) { - my @split_data = split(',',$module_data[$i]); - if (@split_data[0] =~ m/(x|\/|\+|\*|\-)/ && length(@split_data[0]) == 1 ) { - if ( @split_data[0] =~ m/(\/|\+|\*|\-)/ && $synthetic_type eq 'average' ) { - print("[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); - exit 1; + my @id_agents; + my $id_agent; + + if (@ARGV[$#ARGV] eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + @filterdata = (); + $id_agent = $id->{'id_agente'}; + + if ($id_agent > 0) { + + foreach my $i (0 .. $#module_data) { + my @split_data = split(',',$module_data[$i]); + if (@split_data[0] =~ m/(x|\/|\+|\*|\-)/ && length(@split_data[0]) == 1 ) { + if ( @split_data[0] =~ m/(\/|\+|\*|\-)/ && $synthetic_type eq 'average' ) { + print("[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); + exit 1; + } + if (is_numeric(@split_data[1]) == 0) { + next; + } + @data_module = ("",@split_data[0],@split_data[1]); + my $text_data = join(',',@data_module); + push (@filterdata,$text_data); + } + else { + if (scalar(@split_data) == 2) { + @data_module = (safe_output(@split_data[0]),'',safe_output(@split_data[1])); + my $text_data = join(',',@data_module); + push (@filterdata,$text_data); + } + else { + if (length(@split_data[1]) > 1 ) { + print("[ERROR] You can only use +, -, *, / or x, and you use this: @split_data[1] \n\n"); + exit 1; + } + if ( @split_data[1] =~ m/(\/|\+|\*|\-)/ && $synthetic_type eq 'average' ) { + print("[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); + exit 1; + } + if ( $synthetic_type eq 'arithmetic' && $i == 0) { + @data_module = (safe_output(@split_data[0]),'',safe_output(@split_data[2])); + } + else { + @data_module = (safe_output(@split_data[0]),@split_data[1],safe_output(@split_data[2])); + } + my $text_data = join(',',@data_module); + push (@filterdata,$text_data); + } + } } - if (is_numeric(@split_data[1]) == 0) { - next; + + my $module_exists = get_agent_module_id($dbh, $name_module, $id_agent); + non_exist_check($module_exists, 'module name', $name_module); + + $module->{'id_agente'} = $id_agent; + $module->{'nombre'} = safe_input($name_module); + my $id_tipo_modulo = get_db_value ($dbh, "SELECT id_tipo FROM ttipo_modulo WHERE nombre = ?", "generic_data"); + $module->{'id_modulo'} = 5; + $module->{'id_tipo_modulo'} = $id_tipo_modulo; + + my $id_module = db_process_insert($dbh, 'id_agente_modulo', 'tagente_modulo', $module); + + if ($id_module) { + my $result = enterprise_hook('create_synthetic_operations_by_alias', + [$dbh,int($id_module), @filterdata]); + + if ($result) { + + db_do ($dbh, 'INSERT INTO tagente_estado (id_agente_modulo, id_agente, estado, + known_status, last_status, last_known_status, last_try, datos) + VALUES (?, ?, ?, ?, ?, ?, \'1970-01-01 00:00:00\', \'\')', $id_module, $id_agent, 4, 4, 4, 4); + # Update the module status count. When the module is created disabled dont do it + pandora_mark_agent_for_module_update ($dbh, $id_agent); + print("[OK] Created module ID: $id_module \n\n"); + } + else { + #db_do ($dbh, 'DELETE FROM tagente_modulo WHERE id_agente_modulo = ?', $id_module); + print("[ERROR] Problems with creating data module. \n\n"); + } + } + else { + db_do ($dbh, 'DELETE FROM tagente_modulo WHERE nombre = ? AND id_agente = ?', $name_module, $id_agent); + print("[INFO] Problems with creating module \n\n"); } - @data_module = ("",@split_data[0],@split_data[1]); - my $text_data = join(',',@data_module); - push (@filterdata,$text_data); } else { - if (scalar(@split_data) == 2) { - @data_module = (safe_output(@split_data[0]),'',safe_output(@split_data[1])); + print( "[INFO] The agent '$id->{'nombre'}' doesn't exist\n\n"); + } + } + } else { + my $id_agent = int(get_agent_id($dbh,$agent_name)); + + if ($id_agent > 0) { + foreach my $i (0 .. $#module_data) { + my @split_data = split(',',$module_data[$i]); + if (@split_data[0] =~ m/(x|\/|\+|\*|\-)/ && length(@split_data[0]) == 1 ) { + if ( @split_data[0] =~ m/(\/|\+|\*|\-)/ && $synthetic_type eq 'average' ) { + print("[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); + exit 1; + } + if (is_numeric(@split_data[1]) == 0) { + next; + } + @data_module = ("",@split_data[0],@split_data[1]); my $text_data = join(',',@data_module); push (@filterdata,$text_data); } else { - if (length(@split_data[1]) > 1 ) { - print("[ERROR] You can only use +, -, *, / or x, and you use this: @split_data[1] \n\n"); - exit 1; - } - if ( @split_data[1] =~ m/(\/|\+|\*|\-)/ && $synthetic_type eq 'average' ) { - print("[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); - exit 1; - } - if ( $synthetic_type eq 'arithmetic' && $i == 0) { - @data_module = (safe_output(@split_data[0]),'',safe_output(@split_data[2])); + if (scalar(@split_data) == 2) { + @data_module = (safe_output(@split_data[0]),'',safe_output(@split_data[1])); + my $text_data = join(',',@data_module); + push (@filterdata,$text_data); } else { - @data_module = (safe_output(@split_data[0]),@split_data[1],safe_output(@split_data[2])); + if (length(@split_data[1]) > 1 ) { + print("[ERROR] You can only use +, -, *, / or x, and you use this: @split_data[1] \n\n"); + exit 1; + } + if ( @split_data[1] =~ m/(\/|\+|\*|\-)/ && $synthetic_type eq 'average' ) { + print("[ERROR] With this type: $synthetic_type only be allow use this operator: 'x' \n\n"); + exit 1; + } + if ( $synthetic_type eq 'arithmetic' && $i == 0) { + @data_module = (safe_output(@split_data[0]),'',safe_output(@split_data[2])); + } + else { + @data_module = (safe_output(@split_data[0]),@split_data[1],safe_output(@split_data[2])); + } + + my $text_data = join(',',@data_module); + push (@filterdata,$text_data); } - - my $text_data = join(',',@data_module); - push (@filterdata,$text_data); } } - } - my $module_exists = get_agent_module_id($dbh, $name_module, $id_agent); - non_exist_check($module_exists, 'module name', $name_module); - - $module->{'id_agente'} = $id_agent; - $module->{'nombre'} = safe_input($name_module); - my $id_tipo_modulo = get_db_value ($dbh, "SELECT id_tipo FROM ttipo_modulo WHERE nombre = ?", "generic_data"); - $module->{'id_modulo'} = 5; - $module->{'id_tipo_modulo'} = $id_tipo_modulo; - - my $id_module = db_process_insert($dbh, 'id_agente_modulo', 'tagente_modulo', $module); - - if ($id_module) { - my $result = enterprise_hook('create_synthetic_operations', - [$dbh,int($id_module), @filterdata]); - if ($result) { - db_do ($dbh, 'INSERT INTO tagente_estado (id_agente_modulo, id_agente, estado, - known_status, last_status, last_known_status, last_try, datos) - VALUES (?, ?, ?, ?, ?, ?, \'1970-01-01 00:00:00\', \'\')', $id_module, $id_agent, 4, 4, 4, 4); - # Update the module status count. When the module is created disabled dont do it - pandora_mark_agent_for_module_update ($dbh, $id_agent); - print("[OK] The modules are creating ID: $id_module \n\n"); + my $module_exists = get_agent_module_id($dbh, $name_module, $id_agent); + non_exist_check($module_exists, 'module name', $name_module); + + $module->{'id_agente'} = $id_agent; + $module->{'nombre'} = safe_input($name_module); + my $id_tipo_modulo = get_db_value ($dbh, "SELECT id_tipo FROM ttipo_modulo WHERE nombre = ?", "generic_data"); + $module->{'id_modulo'} = 5; + $module->{'id_tipo_modulo'} = $id_tipo_modulo; + + my $id_module = db_process_insert($dbh, 'id_agente_modulo', 'tagente_modulo', $module); + + if ($id_module) { + my $result = enterprise_hook('create_synthetic_operations', + [$dbh,int($id_module), @filterdata]); + if ($result) { + db_do ($dbh, 'INSERT INTO tagente_estado (id_agente_modulo, id_agente, estado, + known_status, last_status, last_known_status, last_try, datos) + VALUES (?, ?, ?, ?, ?, ?, \'1970-01-01 00:00:00\', \'\')', $id_module, $id_agent, 4, 4, 4, 4); + # Update the module status count. When the module is created disabled dont do it + pandora_mark_agent_for_module_update ($dbh, $id_agent); + print("[OK] Created module ID: $id_module \n\n"); + } + else { + db_do ($dbh, 'DELETE FROM tagente_modulo WHERE id_agente_modulo = ?', $id_module); + print("[ERROR] Problems with creating data module. \n\n"); + } } else { - db_do ($dbh, 'DELETE FROM tagente_modulo WHERE id_agente_modulo = ?', $id_module); - print("[ERROR] Problems with creating data module. \n\n"); + db_do ($dbh, 'DELETE FROM tagente_modulo WHERE nombre = ? AND id_agente = ?', $name_module, $id_agent); + print("[INFO] Problems with creating module \n\n"); } } - else { - db_do ($dbh, 'DELETE FROM tagente_modulo WHERE nombre = ? AND id_agente = ?', $name_module, $id_agent); - print("[INFO] Problems with creating module \n\n"); + else { + print( "[INFO] The agent '$agent_name' doesn't exist\n\n"); } } - else { - print( "[INFO] The agent '$agent_name' doesn't exists\n\n"); - } + + } @@ -4146,32 +5095,63 @@ sub cli_get_policy_modules() { ######################################################################## sub cli_get_policies() { - my $agent_name = @ARGV[2]; + my ($agent_name, $use_alias) = @ARGV[2..3]; my $policies; - if (defined($agent_name)) { - my $id_agent = get_agent_id($dbh,$agent_name); - exist_check($id_agent,'agent',$agent_name); + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + if (defined($agent_name)) { + my $id_agent = $id->{'id_agente'}; + exist_check($id_agent,'agent',$agent_name); + + $policies = enterprise_hook('get_agent_policies', [$dbh,$id_agent]); + + if (scalar(@{$policies}) == 0) { + print_log "[INFO] No policies found on agent $id->{'nombre'}\n\n"; + exit; + } + } + else { + $policies = enterprise_hook('get_policies', [$dbh]); + if (scalar(@{$policies}) == 0) { + print_log "[INFO] No policies found\n\n"; + exit; + } + } + + print "agent_name, id_policy, policy_name\n"; + foreach my $module (@{$policies}) { + print $id->{'nombre'}.",".$module->{'id'}.",".safe_output($module->{'name'})."\n"; + } + } + } else { + if (defined($agent_name)) { + my $id_agent = get_agent_id($dbh,$agent_name); + exist_check($id_agent,'agent',$agent_name); + + $policies = enterprise_hook('get_agent_policies', [$dbh,$id_agent]); + + if (scalar(@{$policies}) == 0) { + print_log "[INFO] No policies found on agent '$agent_name'\n\n"; + exit; + } + } + else { + $policies = enterprise_hook('get_policies', [$dbh]); + if (scalar(@{$policies}) == 0) { + print_log "[INFO] No policies found\n\n"; + exit; + } + } - $policies = enterprise_hook('get_agent_policies', [$dbh,$id_agent]); - - if (scalar(@{$policies}) == 0) { - print_log "[INFO] No policies found on agent '$agent_name'\n\n"; - exit; + print "id_policy, policy_name\n"; + foreach my $module (@{$policies}) { + print $module->{'id'}.",".safe_output($module->{'name'})."\n"; } } - else { - $policies = enterprise_hook('get_policies', [$dbh]); - if (scalar(@{$policies}) == 0) { - print_log "[INFO] No policies found\n\n"; - exit; - } - } - - print "id_policy, policy_name\n"; - foreach my $module (@{$policies}) { - print $module->{'id'}.",".safe_output($module->{'name'})."\n"; - } + } ############################################################################## @@ -4180,7 +5160,7 @@ sub cli_get_policies() { ############################################################################## sub cli_get_agents() { - my ($group_name, $os_name, $status, $max_modules, $filter_substring, $policy_name) = @ARGV[2..7]; + my ($group_name, $os_name, $status, $max_modules, $filter_substring, $policy_name, $use_alias) = @ARGV[2..8]; my $condition = ' disabled=0'; @@ -4191,7 +5171,7 @@ sub cli_get_agents() { if($group_name ne '') { $id_group = get_group_id($dbh, $group_name); exist_check($id_group,'group',$group_name); - + $condition .= " AND id_grupo = $id_group "; } @@ -4216,7 +5196,11 @@ sub cli_get_agents() { } if($filter_substring ne '') { - $condition .= " AND nombre LIKE '%".safe_input($filter_substring)."%'"; + if (defined $use_alias and $use_alias eq 'use_alias') { + $condition .= " AND alias LIKE '%".safe_input($filter_substring)."%'"; + } else { + $condition .= " AND nombre LIKE '%".safe_input($filter_substring)."%'"; + } } my @agents = get_db_rows ($dbh, "SELECT * FROM tagente WHERE $condition"); @@ -4229,6 +5213,10 @@ sub cli_get_agents() { my $agent_status; my $head_print = 0; + + use Data::Dumper; + + foreach my $agent (@agents) { if($status ne '') { $agent_status = pandora_get_agent_status($dbh,$agent->{'id_agente'}); @@ -4240,6 +5228,7 @@ sub cli_get_agents() { $head_print = 1; print "id_agent, agent_name\n"; } + print $agent->{'id_agente'}.",".safe_output($agent->{'nombre'})."\n"; } @@ -4254,26 +5243,51 @@ sub cli_get_agents() { ############################################################################## sub cli_delete_conf_file() { - my $agent_name = @ARGV[2]; - + my ($agent_name,$use_alias) = @ARGV[2..3]; + my $conf_deleted = 0; my $md5_deleted = 0; - - if (-e $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf') { - unlink($conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'); - $conf_deleted = 1; - } - if (-e $conf->{incomingdir}.'/md5/'.md5($agent_name).'.md5') { - unlink($conf->{incomingdir}.'/md5/'.md5($agent_name).'.md5'); - $md5_deleted = 1; - } - - if($conf_deleted == 1 || $md5_deleted == 1) { - print_log "[INFO] Local conf files of the agent '$agent_name' has been deleted succesfully\n\n"; - } - else { - print_log "[ERROR] Local conf file of the agent '$agent_name' didn't found\n\n"; - exit; + + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + $agent_name = $id->{'nombre'}; + + if (-e $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf') { + unlink($conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'); + $conf_deleted = 1; + } + if (-e $conf->{incomingdir}.'/md5/'.md5($agent_name).'.md5') { + unlink($conf->{incomingdir}.'/md5/'.md5($agent_name).'.md5'); + $md5_deleted = 1; + } + + if($conf_deleted == 1 || $md5_deleted == 1) { + print_log "[INFO] Local conf files of the agent '$agent_name' has been deleted succesfully\n\n"; + } + else { + print_log "[ERROR] Local conf file of the agent '$agent_name' was not found\n\n"; + exit; + } + } + } else { + if (-e $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf') { + unlink($conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf'); + $conf_deleted = 1; + } + if (-e $conf->{incomingdir}.'/md5/'.md5($agent_name).'.md5') { + unlink($conf->{incomingdir}.'/md5/'.md5($agent_name).'.md5'); + $md5_deleted = 1; + } + + if($conf_deleted == 1 || $md5_deleted == 1) { + print_log "[INFO] Local conf files of the agent '$agent_name' has been deleted succesfully\n\n"; + } + else { + print_log "[ERROR] Local conf file of the agent '$agent_name' was not found\n\n"; + exit; + } } } @@ -4283,14 +5297,29 @@ sub cli_delete_conf_file() { ############################################################################## sub cli_clean_conf_file() { - my $agent_name = @ARGV[2]; + my ($agent_name,$use_alias) = @ARGV[2..3]; my $result; if(defined($agent_name)) { - if (-e $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf') { - $result = enterprise_hook('pandora_clean_conf_file',[$conf, md5($agent_name)]); - if($result != -1) { - print_log "[INFO] Conf file '".$conf->{incomingdir}.'/conf/'.md5($agent_name).".conf has been cleaned'\n\n"; + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + $agent_name = $id->{'nombre'}; + + if (-e $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf') { + $result = enterprise_hook('pandora_clean_conf_file',[$conf, md5($agent_name)]); + if($result != -1) { + print_log "[INFO] Conf file '".$conf->{incomingdir}.'/conf/'.md5($agent_name).".conf has been cleaned'\n\n"; + } + } + } + } else { + if (-e $conf->{incomingdir}.'/conf/'.md5($agent_name).'.conf') { + $result = enterprise_hook('pandora_clean_conf_file',[$conf, md5($agent_name)]); + if($result != -1) { + print_log "[INFO] Conf file '".$conf->{incomingdir}.'/conf/'.md5($agent_name).".conf has been cleaned'\n\n"; + } } } } @@ -4367,23 +5396,46 @@ sub cli_disable_policy_alerts() { ############################################################################## sub cli_policy_add_agent() { - my ($agent_name, $policy_name) = @ARGV[2..3]; + my ($agent_name, $policy_name, $use_alias) = @ARGV[2..4]; - my $agent_id = get_agent_id($dbh,$agent_name); - exist_check($agent_id,'agent',$agent_name); - - my $policy_id = enterprise_hook('get_policy_id',[$dbh, safe_input($policy_name)]); - exist_check($policy_id,'policy',$policy_name); + if (defined $use_alias and $use_alias eq 'use_alias') { + my @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + foreach my $id (@id_agents) { + my $agent_id = $id->{'id_agente'}; + exist_check($agent_id,'agent',$agent_name); + + my $policy_id = enterprise_hook('get_policy_id',[$dbh, safe_input($policy_name)]); + exist_check($policy_id,'policy',$policy_name); + + # Add the agent to policy + my $policy_agent_id = enterprise_hook('pandora_policy_add_agent',[$policy_id, $agent_id, $dbh]); + + if($policy_agent_id == -1) { + print_log "[ERROR] A problem has been ocurred adding agent $id->{'nombre'} to policy '$policy_name'\n\n"; + } + else { + print_log "[INFO] Added agent $id->{'nombre'} to policy $policy_name. Is necessary to apply the policy in order to changes take effect.\n\n"; + } + } + } else { + my $agent_id = get_agent_id($dbh,$agent_name); + exist_check($agent_id,'agent',$agent_name); - # Add the agent to policy - my $policy_agent_id = enterprise_hook('pandora_policy_add_agent',[$policy_id, $agent_id, $dbh]); - - if($policy_agent_id == -1) { - print_log "[ERROR] A problem has been ocurred adding agent '$agent_name' to policy '$policy_name'\n\n"; - } - else { - print_log "[INFO] Added agent '$agent_name' to policy '$policy_name'. Is necessary to apply the policy in order to changes take effect.\n\n"; + my $policy_id = enterprise_hook('get_policy_id',[$dbh, safe_input($policy_name)]); + exist_check($policy_id,'policy',$policy_name); + + # Add the agent to policy + my $policy_agent_id = enterprise_hook('pandora_policy_add_agent',[$policy_id, $agent_id, $dbh]); + + if($policy_agent_id == -1) { + print_log "[ERROR] A problem has been ocurred adding agent '$agent_name' to policy '$policy_name'\n\n"; + } + else { + print_log "[INFO] Added agent '$agent_name' to policy '$policy_name'. Is necessary to apply the policy in order to changes take effect.\n\n"; + } } + } ############################################################################## @@ -4609,11 +5661,6 @@ sub cli_update_group() { print_log "[INFO] Updated group '$group_id'\n\n"; } } - - - - - } @@ -4622,47 +5669,79 @@ sub cli_update_group() { # Related option: --locate_agent ############################################################################### sub cli_locate_agent () { - my ($agent_name) = @ARGV[2]; + my ($agent_name, $use_alias) = @ARGV[2..3]; if (is_metaconsole($conf) == 1) { - my $agents_server = enterprise_hook('get_metaconsole_agent',[$dbh, $agent_name]); - - if (scalar(@{$agents_server}) != 0) { - foreach my $agent (@{$agents_server}) { - #my $server = enterprise_hook('get_metaconsole_setup_server_id',[$dbh, $agent->{'server_name'}]); - print $agent->{'id_tmetaconsole_setup'} . "\n"; - } - } - else { + if (defined $use_alias and $use_alias eq 'use_alias') { my $servers = enterprise_hook('get_metaconsole_setup_servers',[$dbh]); my @servers_id = split(',',$servers); my @list_servers; my $list_names_servers; + my @id_agents; foreach my $server (@servers_id) { my $dbh_metaconsole = enterprise_hook('get_node_dbh',[$conf, $server, $dbh]); - my $agent_id = get_agent_id($dbh_metaconsole,$agent_name); + @id_agents = get_agent_ids_from_alias($dbh_metaconsole,$agent_name); - if ($agent_id == -1) { - next; - } - else { - push @list_servers,$server; + foreach my $id (@id_agents) { + if ($id->{'id_agente'} == -1) { + next; + } + else { + push @list_servers,$server; + last; + } } } if (scalar(@list_servers) > 0) { $list_names_servers = join(',',@list_servers); - print_log "[INFO] The agent: $agent_name find in server with IDS: $list_names_servers\n\n"; + print_log "[INFO] One or more agents with the alias '$agent_name' were found in server with IDS: $list_names_servers\n\n"; } else { - print_log "[ERROR] This agent: $agent_name not find in any node\n\n"; + print_log "[ERROR] No agent with alias '$agent_name' found in any node\n\n"; + } + } else { + my $agents_server = enterprise_hook('get_metaconsole_agent',[$dbh, $agent_name]); + + if (scalar(@{$agents_server}) != 0) { + foreach my $agent (@{$agents_server}) { + #my $server = enterprise_hook('get_metaconsole_setup_server_id',[$dbh, $agent->{'server_name'}]); + print $agent->{'id_tmetaconsole_setup'} . "\n"; + } + } + else { + my $servers = enterprise_hook('get_metaconsole_setup_servers',[$dbh]); + my @servers_id = split(',',$servers); + my @list_servers; + my $list_names_servers; + foreach my $server (@servers_id) { + my $dbh_metaconsole = enterprise_hook('get_node_dbh',[$conf, $server, $dbh]); + + my $agent_id = get_agent_id($dbh_metaconsole,$agent_name); + + if ($agent_id == -1) { + next; + } + else { + push @list_servers,$server; + } + } + + if (scalar(@list_servers) > 0) { + $list_names_servers = join(',',@list_servers); + print_log "[INFO] Agent '$agent_name' found in server with IDS: $list_names_servers\n\n"; + } + else { + print_log "[ERROR] Agent '$agent_name' not found in any node\n\n"; + } } } + } else { - print_log "[ERROR] This functions only working in metaconsole system\n\n"; + print_log "[ERROR] This function can only be used in metaconsole\n\n"; } } @@ -4816,9 +5895,16 @@ sub cli_stop_downtime () { exist_check($downtime_id,'planned downtime',$downtime_id); my $current_time = time; - my $downtime_date_to = get_db_value ($dbh, 'SELECT date_to FROM tplanned_downtime WHERE id=?', $downtime_id); - if($current_time >= $downtime_date_to) { + my $data = get_db_single_row ($dbh, 'SELECT date_to, type_execution, executed FROM tplanned_downtime WHERE id=?', $downtime_id); + + if( $data->{'type_execution'} eq 'periodically' && $data->{'executed'} == 1){ + print_log "[ERROR] Planned_downtime '$downtime_name' cannot be stopped.\n"; + print_log "[INFO] Periodical and running planned downtime cannot be stopped.\n\n"; + exit; + } + + if($current_time >= $data->{'date_to'}) { print_log "[INFO] Planned_downtime '$downtime_name' is already stopped\n\n"; exit; } @@ -4835,7 +5921,7 @@ sub cli_stop_downtime () { # Related option: --get_module_data ############################################################################### sub cli_module_get_data () { - my ($agent_name, $module_name, $interval, $csv_separator) = @ARGV[2..5]; + my ($agent_name, $module_name, $interval, $csv_separator, $use_alias) = @ARGV[2..6]; $csv_separator = '|' unless defined($csv_separator); @@ -4843,57 +5929,112 @@ sub cli_module_get_data () { print_log "[ERROR] Interval must be a possitive value\n\n"; exit; } + + my @id_agents; - - - my $agent_id = get_agent_id($dbh,$agent_name); - exist_check($agent_id, 'agent name', $agent_name); - - my $module_id = get_agent_module_id($dbh, $module_name, $agent_id); - exist_check($module_id, 'module name', $module_name); - - my $id_agent_module = get_agent_module_id ($dbh, $module_name, $agent_id); - - my $module_type_id = get_db_value($dbh, - "SELECT id_tipo_modulo FROM tagente_modulo WHERE id_agente_modulo = ?", - $id_agent_module); - - my $module_type = get_db_value($dbh, - "SELECT nombre FROM ttipo_modulo WHERE id_tipo = ?", - $module_type_id); - - my @data = NULL; - if ($module_type eq "log4x") { - @data = get_db_rows ($dbh, "SELECT utimestamp, datos - FROM tagente_datos_log4x - WHERE id_agente_modulo = $id_agent_module - AND utimestamp > (UNIX_TIMESTAMP(NOW()) - $interval) - ORDER BY utimestamp DESC"); - } - elsif ($module_type =~ m/_string/) { - print("aaaa\n"); - @data = get_db_rows ($dbh, "SELECT utimestamp, datos - FROM tagente_datos_string - WHERE id_agente_modulo = $id_agent_module - AND utimestamp > (UNIX_TIMESTAMP(NOW()) - $interval) - ORDER BY utimestamp DESC"); - } - else { - @data = get_db_rows ($dbh, "SELECT utimestamp, datos - FROM tagente_datos - WHERE id_agente_modulo = $id_agent_module - AND utimestamp > (UNIX_TIMESTAMP(NOW()) - $interval) - ORDER BY utimestamp DESC"); - } - - - - foreach my $data_timestamp (@data) { - print $data_timestamp->{'utimestamp'}; - print $csv_separator; - print $data_timestamp->{'datos'}; - print "\n"; + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + my $agent_id; + + foreach my $id (@id_agents) { + $agent_id = $id->{'id_agente'}; # se hace para cada agente + exist_check($agent_id, 'agent name', $agent_name); + + my $module_id = get_agent_module_id($dbh, $module_name, $agent_id); # se hace para ada agente + if ($module_id == -1) { + next; + } + + my $id_agent_module = get_agent_module_id ($dbh, $module_name, $agent_id); # 6 + + my $module_type_id = get_db_value($dbh, + "SELECT id_tipo_modulo FROM tagente_modulo WHERE id_agente_modulo = ?", + $id_agent_module); # se hace para cada agente + + my $module_type = get_db_value($dbh, + "SELECT nombre FROM ttipo_modulo WHERE id_tipo = ?", + $module_type_id); # se hace para cada agente + + my @data = NULL; + if ($module_type eq "log4x") { + @data = get_db_rows ($dbh, "SELECT utimestamp, datos + FROM tagente_datos_log4x + WHERE id_agente_modulo = $id_agent_module + AND utimestamp > (UNIX_TIMESTAMP(NOW()) - $interval) + ORDER BY utimestamp DESC"); + } + elsif ($module_type =~ m/_string/) { + @data = get_db_rows ($dbh, "SELECT utimestamp, datos + FROM tagente_datos_string + WHERE id_agente_modulo = $id_agent_module + AND utimestamp > (UNIX_TIMESTAMP(NOW()) - $interval) + ORDER BY utimestamp DESC"); + } + else { + @data = get_db_rows ($dbh, "SELECT utimestamp, datos + FROM tagente_datos + WHERE id_agente_modulo = $id_agent_module + AND utimestamp > (UNIX_TIMESTAMP(NOW()) - $interval) + ORDER BY utimestamp DESC"); + } + + foreach my $data_timestamp (@data) { + print $data_timestamp->{'utimestamp'}; + print $csv_separator; + print $data_timestamp->{'datos'}; + print "\n"; + } + } + + } else { + my $agent_id = get_agent_id($dbh,$agent_name); # se hace para cada agente + exist_check($agent_id, 'agent name', $agent_name); + + my $module_id = get_agent_module_id($dbh, $module_name, $agent_id); # se hace para ada agente + exist_check($module_id, 'module name', $module_name); + + my $id_agent_module = get_agent_module_id ($dbh, $module_name, $agent_id); # 6 + + my $module_type_id = get_db_value($dbh, + "SELECT id_tipo_modulo FROM tagente_modulo WHERE id_agente_modulo = ?", + $id_agent_module); # se hace para cada agente + + my $module_type = get_db_value($dbh, + "SELECT nombre FROM ttipo_modulo WHERE id_tipo = ?", + $module_type_id); # se hace para cada agente + + my @data = NULL; + if ($module_type eq "log4x") { + @data = get_db_rows ($dbh, "SELECT utimestamp, datos + FROM tagente_datos_log4x + WHERE id_agente_modulo = $id_agent_module + AND utimestamp > (UNIX_TIMESTAMP(NOW()) - $interval) + ORDER BY utimestamp DESC"); + } + elsif ($module_type =~ m/_string/) { + @data = get_db_rows ($dbh, "SELECT utimestamp, datos + FROM tagente_datos_string + WHERE id_agente_modulo = $id_agent_module + AND utimestamp > (UNIX_TIMESTAMP(NOW()) - $interval) + ORDER BY utimestamp DESC"); + } + else { + @data = get_db_rows ($dbh, "SELECT utimestamp, datos + FROM tagente_datos + WHERE id_agente_modulo = $id_agent_module + AND utimestamp > (UNIX_TIMESTAMP(NOW()) - $interval) + ORDER BY utimestamp DESC"); + } + + foreach my $data_timestamp (@data) { + print $data_timestamp->{'utimestamp'}; + print $csv_separator; + print $data_timestamp->{'datos'}; + print "\n"; + } } + exit; } @@ -6023,7 +7164,7 @@ sub pandora_manage_main ($$$) { cli_create_agent(); } elsif ($param eq '--delete_agent') { - param_check($ltotal, 1); + param_check($ltotal, 2, 1); cli_delete_agent(); } elsif ($param eq '--create_data_module') { @@ -6031,7 +7172,7 @@ sub pandora_manage_main ($$$) { cli_create_data_module(0); } elsif ($param eq '--create_web_module') { - param_check($ltotal, 38, 35); + param_check($ltotal, 39, 36); cli_create_web_module(0); } @@ -6048,19 +7189,19 @@ sub pandora_manage_main ($$$) { cli_module_group_synch(); } elsif ($param eq '--create_network_module') { - param_check($ltotal, 32, 20); + param_check($ltotal, 33, 21); cli_create_network_module(0); } elsif ($param eq '--create_snmp_module') { - param_check($ltotal, 40, 28); + param_check($ltotal, 41, 29); cli_create_snmp_module(0); } elsif ($param eq '--create_plugin_module') { - param_check($ltotal, 34, 19); + param_check($ltotal, 35, 20); cli_create_plugin_module(0); } elsif ($param eq '--delete_module') { - param_check($ltotal, 2); + param_check($ltotal, 3, 1); cli_delete_module(); } elsif ($param eq '--delete_not_policy_modules') { @@ -6068,23 +7209,23 @@ sub pandora_manage_main ($$$) { cli_delete_not_policy_modules(); } elsif ($param eq '--create_template_module') { - param_check($ltotal, 3); + param_check($ltotal, 4, 1); cli_create_template_module(); } elsif ($param eq '--delete_template_module') { - param_check($ltotal, 3); + param_check($ltotal, 4, 1); cli_delete_template_module(); } elsif ($param eq '--create_template_action') { - param_check($ltotal, 6, 2); + param_check($ltotal, 7, 3); cli_create_template_action(); } elsif ($param eq '--delete_template_action') { - param_check($ltotal, 4); + param_check($ltotal,5, 1); cli_delete_template_action(); } elsif ($param eq '--data_module') { - param_check($ltotal, 6, 1); + param_check($ltotal, 7, 2); cli_data_module(); } elsif ($param eq '--create_user') { @@ -6108,11 +7249,11 @@ sub pandora_manage_main ($$$) { cli_delete_profile(); } elsif ($param eq '--create_event') { - param_check($ltotal, 18, 15); + param_check($ltotal, 19, 16); cli_create_event(); } elsif ($param eq '--validate_event') { - param_check($ltotal, 7, 6); + param_check($ltotal, 8, 7); cli_validate_event(); } elsif ($param eq '--validate_event_id') { @@ -6132,7 +7273,7 @@ sub pandora_manage_main ($$$) { cli_create_incident(); } elsif ($param eq '--delete_data') { - param_check($ltotal, 3, 1); + param_check($ltotal, 4, 2); cli_delete_data($ltotal); } elsif ($param eq '--apply_policy') { @@ -6156,7 +7297,7 @@ sub pandora_manage_main ($$$) { cli_update_group(); } elsif ($param eq '--add_agent_to_policy') { - param_check($ltotal, 2); + param_check($ltotal, 3, 1); cli_policy_add_agent(); } elsif ($param eq '--remove_agent_from_policy') { @@ -6180,7 +7321,7 @@ sub pandora_manage_main ($$$) { cli_user_add_profile(); } elsif ($param eq '--get_module_data') { - param_check($ltotal, 4, 1); + param_check($ltotal, 5, 2); cli_module_get_data(); } elsif ($param eq '--add_collection_to_policy') { @@ -6196,7 +7337,7 @@ sub pandora_manage_main ($$$) { cli_create_policy(); } elsif ($param eq '--create_policy_data_module') { - param_check($ltotal, 28, 20); + param_check($ltotal, 29, 21); cli_create_data_module(1); } elsif ($param eq '--create_policy_web_module') { @@ -6244,7 +7385,7 @@ sub pandora_manage_main ($$$) { cli_alert_template_update(); } elsif ($param eq '--update_module') { - param_check($ltotal, 4); + param_check($ltotal, 6, 2); cli_module_update(); } elsif ($param eq '--exec_from_file') { @@ -6270,11 +7411,11 @@ sub pandora_manage_main ($$$) { cli_get_module_id(); } elsif ($param eq '--get_agent_group') { - param_check($ltotal, 1); + param_check($ltotal, 2, 1); cli_get_agent_group(); } elsif ($param eq '--get_agent_group_id') { - param_check($ltotal, 1); + param_check($ltotal, 2, 1); cli_get_agent_group_id(); } elsif ($param eq '--get_agents_module_current_data') { @@ -6282,7 +7423,7 @@ sub pandora_manage_main ($$$) { cli_get_agents_module_current_data(); } elsif ($param eq '--get_agent_modules') { - param_check($ltotal, 1); + param_check($ltotal, 2, 1); cli_get_agent_modules(); } elsif ($param eq '--get_policy_modules') { @@ -6290,23 +7431,23 @@ sub pandora_manage_main ($$$) { cli_get_policy_modules(); } elsif ($param eq '--get_policies') { - param_check($ltotal, 1, 1); + param_check($ltotal, 2, 2); cli_get_policies(); } elsif ($param eq '--get_agents') { - param_check($ltotal, 6, 6); + param_check($ltotal, 7, 7); cli_get_agents(); } elsif ($param eq '--delete_conf_file') { - param_check($ltotal, 1); + param_check($ltotal, 2, 1); cli_delete_conf_file(); } elsif ($param eq '--clean_conf_file') { - param_check($ltotal, 1, 1); + param_check($ltotal, 2, 1); cli_clean_conf_file(); } elsif ($param eq '--update_agent') { - param_check($ltotal, 3); + param_check($ltotal, 4, 1); cli_agent_update(); } elsif ($param eq '--get_bad_conf_files') { @@ -6314,7 +7455,7 @@ sub pandora_manage_main ($$$) { cli_get_bad_conf_files(); } elsif ($param eq '--create_network_module_from_component') { - param_check($ltotal, 2); + param_check($ltotal, 3, 1); cli_create_network_module_from_component(); } elsif ($param eq '--create_network_component') { @@ -6366,7 +7507,7 @@ sub pandora_manage_main ($$$) { cli_delete_special_day(); } elsif ($param eq '--create_data_module_from_local_component') { - param_check($ltotal, 2); + param_check($ltotal, 3, 1); cli_create_data_module_from_local_component(); } elsif ($param eq '--create_local_component') { @@ -6414,7 +7555,7 @@ sub pandora_manage_main ($$$) { cli_set_delete_planned_downtime(); } elsif ($param eq '--locate_agent') { - param_check($ltotal, 1); + param_check($ltotal, 2, 1); cli_locate_agent(); } elsif ($param eq '--create_visual_console') { @@ -6638,22 +7779,53 @@ sub cli_add_collection_to_policy () { ############################################################################## sub cli_create_data_module_from_local_component() { - my ($agent_name, $component_name) = @ARGV[2..3]; - - my $agent_id = get_agent_id($dbh,$agent_name); - exist_check($agent_id,'agent',$agent_name); + my ($agent_name, $component_name, $use_alias) = @ARGV[2..4]; + + my @id_agents; + + if (defined $use_alias and $use_alias eq 'use_alias') { + @id_agents = get_agent_ids_from_alias($dbh,$agent_name); + + my $agent_id; + + foreach my $id (@id_agents) { + $agent_id = $id->{'id_agente'}; + exist_check($agent_id,'agent',$agent_name); + + my $lc_id = pandora_get_local_component_id($dbh, $component_name); + exist_check($lc_id,'local component',$component_name); + + my $module_exists = get_agent_module_id($dbh, $component_name, $agent_id); + if ($module_exists ne -1) { + next; + } + + # Get local component data + my $component = get_db_single_row ($dbh, 'SELECT * FROM tlocal_component WHERE id = ?', $lc_id); + + print_log "[INFO] Creating module from local component '$component_name'\n\n"; + + #~ pandora_create_module_from_local_component ($conf, $component, $agent_id, $dbh); + enterprise_hook('pandora_create_module_from_local_component',[$conf, $component, $agent_id, $dbh]); + } + } else { + my $agent_id = get_agent_id($dbh,$agent_name); + exist_check($agent_id,'agent',$agent_name); + + my $lc_id = pandora_get_local_component_id($dbh, $component_name); + exist_check($lc_id,'local component',$component_name); - my $lc_id = pandora_get_local_component_id($dbh, $component_name); - exist_check($lc_id,'local component',$component_name); - - my $module_exists = get_agent_module_id($dbh, $component_name, $agent_id); - non_exist_check($module_exists, 'module name', $component_name); - - # Get local component data - my $component = get_db_single_row ($dbh, 'SELECT * FROM tlocal_component WHERE id = ?', $lc_id); - - #~ pandora_create_module_from_local_component ($conf, $component, $agent_id, $dbh); - enterprise_hook('pandora_create_module_from_local_component',[$conf, $component, $agent_id, $dbh]); + my $module_exists = get_agent_module_id($dbh, $component_name, $agent_id); + non_exist_check($module_exists, 'module name', $component_name); + + # Get local component data + my $component = get_db_single_row ($dbh, 'SELECT * FROM tlocal_component WHERE id = ?', $lc_id); + + print_log "[INFO] Creating module from local component '$component_name'\n\n"; + + #~ pandora_create_module_from_local_component ($conf, $component, $agent_id, $dbh); + enterprise_hook('pandora_create_module_from_local_component',[$conf, $component, $agent_id, $dbh]); + } } ############################################################################## # Create policy data module from local component. diff --git a/pandora_server/util/pandora_smpp.pl b/pandora_server/util/pandora_smpp.pl index af85d496f5..720d0e9589 100755 --- a/pandora_server/util/pandora_smpp.pl +++ b/pandora_server/util/pandora_smpp.pl @@ -19,7 +19,7 @@ Usage: $0 -server <smsc_server:port> -user <user_id> -password <user_password> -source <source_number> -destination <destination_numbers> -message <short_message> [OPTIONS] -- <destination_numbers> Comma separated list of destination numbers (+123456789,+234567891,...) +- <destination_numbers> Comma separated list of destination numbers (123456789,234567891,...) OPTIONS: @@ -45,7 +45,7 @@ OPTIONS: Example: -$0 -server 192.168.1.50:2775 -user myuser -password mypassword -source +123456789 -destination +234567891 -message "Content of SMS message" +$0 -server 192.168.1.50:2775 -user myuser -password mypassword -source 123456789 -destination 234567891 -message "Content of SMS message" EO_H @@ -85,7 +85,7 @@ if (!$config->{'message'}){ my ($smsc_server, $smsc_port) = split /:/, $config->{'server'}; -my @destination_numbers = $config->{'destination'}; +my @destination_numbers = split /,/, $config->{'destination'}; if (!$smsc_port){ $smsc_port = 2775;